var webUrl = "";
	var websocket = null;
	var myWebrtc = null;
	var register = false;
	var username="";//账号--需要输入
	var password="";//账号密码--需要输入
	var host="";//服务器地址--需要输入
	var sysUserId="";//userid
	var hostNoPort=""
	var registerSIP = "";//是否注册SIP话机
	var leftControl = "";//左控制话机
	var leftPwd = "";//左分机密码
	var autoCall = false;//默认不自动接听
	var acceptModal = 'auto'//接听方式 默认
	var callOut = false;//是否是呼出
	var comExten = '';
	var extenStatus = '';
	var extenName = '';
	var extenIP = '';
	var method="";//请求类型
	var exten = '';//操作分机
	var pstnnumber = '';//外线号码
	var caller="";//左话机
	var callee = "";//右话机
	var timeoutSec = 30;//心跳检测时间（秒）
	var heartbeatId=-1;//心跳事件ID
	var loseHeartbeat=0;//心跳丢包次数
	
	var confList = []//全部会议
	var timeId = "";
	var timeOne = "";
	var path = "";
	var fristLoad = 0;
	var videoExten = "";
	//视频模块的token
	var token = ""
	//http
	var httpProto = 'http'
	var wsProto = 'ws'
	var wsPort = '7066'
	//记录用户选中的左、右话机（默认是左话机）
	var isRightCall = false;
	var isEdit = false;//是否是编辑广播任务弹框，添加则高级记忆
	var isNoticeEdit = false;//是否是编辑调度通知弹框，添加则高级记忆
	var isCheckEdit = false;//是否是编辑自检任务弹框
	var isChimeEdit = false;//是否是编辑报时任务弹框
	var leftMenuForControl = [];//主控台左侧菜单
	var userId = "";//用户唯一标识Id
	var isAdmin = "";//当前用户是否为管理员
	var deptId = "";//当前用户所处的分区id
	var deptIdName = "";//当前用户所处的分区名称
	var checkType = "-1";//记录自检左侧列表的数据
	var checkValue = "";
	var chimeType = "-1";//记录整点报时左侧列表数据
	var chimeValue = "";
	var allDeptData = [];//所属分区数据(多级分区)
	var allDeptList = [];//所属分区数据
	var checkExtens = "";

	var mapStatusList = []//分机状态合集

	//预案
	var devicesList=[];//全部终端
	var actionPlanList=[];//预案联动数据
	var alarmDevices=[];//（预案）网关
	var planAllCamera=[];//（预案）摄像头
	var broad_list=[];//（预案）广播
	var broadlink_data=[];
	var video_list=[];//（预案）视频
	var videolink_data=[];
	var smslink_data=[];//（预案）短信
	var notice_list=[];//（预案）通知
	var noticelink_data=[];
	var conf_list=[];//（预案）通知
	var conflink_data=[];
	var intercom={id:0,ppId: 0,linkType: 0,extNum: ''};//（预案）对讲
	var authForAll = "";
	let allAudioList = [];//存放提示音列表

	//视频模块已占用的视频窗口
	var videoOccupyList = []; 
	//是否是手动选择摄像头窗口
	var redborderType = false;
	
	//加上token
	// $(document).ajaxSend(function(event, jqxhr, settings) {
	// 	console.log('login.json', settings)
	// 	if(settings.url.indexOf('control/20140901/infs/login.json') === -1 && jqxhr.getRequestHeader == undefined && localStorage.rh_token){
	// 		jqxhr.setRequestHeader('Authorization', localStorage.rh_token)
	// 	}
	// })
	function $nsGcmWsDisInit(){
		var pathName = document.location.pathname;
		var index = pathName.substr(1).lastIndexOf("/");
		var result = pathName.substr(0,index+1);
		path = result;
		username = localStorage.rh_username
		password = localStorage.rh_password
		leftPwd = localStorage.rh_lpd
		host = localStorage.rh_ip
		sysUserId=localStorage.rh_sysUserId
		token=localStorage.rh_tokenB
		hostNoPort = host
		var baseForAll = new Base64();
		authForAll = baseForAll.encode(username+":"+password)
		if (host) {
			hostNoPort = host.split(':')[0]
		}

		registerSIP = localStorage.rh_registerSIP
		var left = localStorage.rh_leftControl
		if (left) {
			if (left.indexOf('@') > -1) {
				leftControl = left.split('@')[0]
			} else {
				leftControl = left
			}
		}

		if (window.location.protocol) {
			httpProto = window.location.protocol.indexOf('https')>-1?'https':'http'
		}
		if (httpProto.indexOf('https')>-1) {
			wsProto = 'wss'
			wsPort = '7067'
		}

		if(host == '' || host == null || host == undefined){
			// window.location.href = result+"/main.html"
		}
		//判断当前浏览器是否支持WebSocket
		if ('WebSocket' in window) {
			webUrl = wsProto + '://'+host+'/DisWebSocket/websocket'
		    websocket = new WebSocket(webUrl);//websoket地址--需要输入
		}
		else {
		    alert('当前浏览器 Not support websocket')
		}
		//连接发生错误的回调方法
		websocket.onerror = function () {
		    //setMessageInnerHTML("WebSocket连接发生错误");
		};

		//连接成功建立的回调方法
		websocket.onopen = function () {
			console.log('WebSocket连接成功!!!!!')
		    //setMessageInnerHTML("WebSocket连接成功");
			setTimeout(login(),1000);
			// getFjList(username,password);
			// getAudioList();
			// getPlayList();
			// getPstn();
			// getSipCounts();
		}
		//接收到消息的回调方法
		websocket.onmessage = function (event) {
			//setMessageInnerHTML(event.data);
			var jsonStr=JSON.parse(event.data);
			// console.log('接收到消息的回调方法 websocket.onmessage', jsonStr.method)
			onEvent(jsonStr.type,jsonStr.method,jsonStr);

		}
		//连接关闭的回调方法
		websocket.onclose = function () {
		    //setMessageInnerHTML("WebSocket连接关闭");
		}
		//注册SIP话机
		if (registerSIP == '1') {
			myWebrtc = new MyWebrtc();
			var SIPURL = wsProto + '://'+host+':'+wsPort
			if(host.indexOf(":") != -1){
				SIPURL = wsProto + '://'+host.split(":")[0]+':'+wsPort
			}
			myWebrtc.jssipAgent(SIPURL,leftControl,host,leftPwd,null,null,null,(val)=>{
				register = val
				if (val) {
					console.log('sip话机注册成功！')
					$('.sipMobile').css('display','inline')
				}
			},'webrtcVideo','myVideo',openVideoLayer,closeVideoLayer)
		}
		
		// checkDeviceSupport(function(isSup){
		// 	if (!isSup) {
		// 		$('#video_option').attr('hidden','true')
		// 		$('#auto_option').attr('hidden','true')
		// 		//隐藏可选接听按钮
		// 		$('#vioceSip').hide()
		// 		$('#videoSip').hide()
		// 		$('#autoSip').show()
		// 		//设置选择语音
		// 		acceptModal = 'audio'
		// 		alert('您的设备不支持视频！')
		// 	}
		// })
	}

	var videoIndex = null
	function openVideoLayer(callback){

		closeVideoLayer()
		layui.use('layer',function(){
		videoIndex = layer.open({
				type:1,
				title:'视频通话',
				shadeClose:true,
				shade:false,
				maxmin:true,
				closeBtn:0,
				area:'800px',
				resize:false,
				offset: 'rb',
				//content:'<div style="text-align:center;">'+html+'</div><br/>'
				content:parent.$('#videoLayer'),
				success:function(layero,index){
					callback()
					//$.alert("模拟返回成功")
					//
					console.log("layero："+layero);
				let currentTop = $(layero).position().top 
				var window_height  = $(window).height();
				// 目前高度 - 视口高度
				let gap  = (currentTop + 647) - window_height ;

				if(gap > 0){
					$(layero).css("top",currentTop - gap +"px");
				}

				},
				full(dom){
					var width = dom.width()
					var height = dom.height()
					document.getElementById('mvId').style.width = width + 'px'
					document.getElementById('mvId').style.height = height - 42 + 'px'

					var wii = $('#myVideo').width()
					var hii = $('#myVideo').height()
					document.getElementById('myVideo').style.width = wii + 100 + 'px'
					document.getElementById('myVideo').style.height = hii + 75 + 'px'
				},
				min(){

				},
				restore(dom){
					var width = dom.width()
					var height = dom.height()
					document.getElementById('mvId').style.width = width + 'px'
					document.getElementById('mvId').style.height = height -42 + 'px'

					var wii = $('#myVideo').width()
					var hii = $('#myVideo').height()
					if (wii>300) {
						document.getElementById('myVideo').style.width = wii - 100 + 'px'
						document.getElementById('myVideo').style.height = hii - 75 + 'px'
					}else{
						document.getElementById('myVideo').style.width =  '220px'
						document.getElementById('myVideo').style.height =  '140px'
					}
					
				}
			})
		})
	}

	function closeVideoLayer(){
		//修复高度问题
		//dom 为layer [800,647]
		var width = 800
		var height = 647
		document.getElementById('mvId').style.width = width + 'px'
		document.getElementById('mvId').style.height = height -42 + 'px'

		var wii = $('#myVideo').width()
		var hii = $('#myVideo').height()
		if (wii>300) {
			document.getElementById('myVideo').style.width = wii - 100 + 'px'
			document.getElementById('myVideo').style.height = hii - 75 + 'px'
		}else{
			document.getElementById('myVideo').style.width =  '220px'
			document.getElementById('myVideo').style.height =  '140px'
		}

		if (videoIndex) {
			layui.use('layer',function(){
				layer.close(videoIndex)
			})
		}
	}

	//判断是否有摄像头
	function checkDeviceSupport(callback) {
		var isSupportVideo = false
		navigator.mediaDevices.getUserMedia({
			video:true,
			audio:true
		}).then(stream=>{
			isSupportVideo = true
			callback(isSupportVideo)
		}).catch(error=>{
			isSupportVideo = false
			callback(isSupportVideo)
		})
	}

	//填充时间
	function curTime(){
		var date = new Date();
		var curtime = dateFormat('YYYY-mm-dd HH:MM:SS',date)
		$('#curtime').html("当前时间："+curtime)
	}
	var broid = "";
	
	var openFile = function(event) {
	    var input = event.target;
	    var reader = new FileReader();
	    reader.onload = function() {
	        if(reader.result) {
	            //显示文件内容
	            //$("#output").html(reader.result);
				$('#filepath').val(reader.result)
	        }
	    };
	    reader.readAsText(input.files[0]);
	};
	var openFileTwo = function(event,file) {
		if (file.name) {
			let exs = file.name.substring(file.name.indexOf('.'), file.name.length)
			if (exs !== '.txt') {
				$.alert('文件类型错误')
				return false
			}
		}
		var input = event.target;
		var reader = new FileReader();
		reader.onload = function() {
			if(reader.result) {
				let res = reader.result;
				let info = ''
				let flag = true
				let importArr = []
				let arr = res.split(',')
				let reg = /^\d+(\.\d+)?$/
				arr.forEach(item => {
					if (!reg.test(item)) {
						flag = false
						info += item
					} else {
						importArr.push(item)
					}
				})
				if (flag) {
					let _arr = $('#isSelectNum').val().split(',')
					let arrOne = Array.from(new Set([...importArr,..._arr]))
					let str = ''
					arrOne.forEach(item => {
						if (item) {
							str += item + ','
						}
					})
					$('#isSelectNum').val(str.substring(0, str.length - 1))
				} else {
					$.alert('不是数字')
					return;
				}
				//显示文件内容
				//$("#output").html(reader.result);
			}
		};
		reader.readAsText(input.files[0]);
	};
	var openFileOne = function(event,data) {
		if (data[0].name) {
			let exs = data[0].name.substring(data[0].name.indexOf('.'), data[0].name.length)
			if (exs !== '.txt') {
				$.alert('文件类型错误')
				return false
			}
		}
		// 创建空的formData对象
		var formData = new FormData();
		// 将用户选择的文件追加到formData表单对象中
		formData.append('file',data[0])
		formData.append('language','zh-CN')
		// console.log(formData)
		// 创建ajax对象
		var xhr = new XMLHttpRequest();
		// 对ajax对象进行配置
		xhr.open('post',httpProto+'://'+host+'/system-service/api-v1.0/sysGeneral/parseTxt')
		xhr.setRequestHeader("Authorization",token);
		xhr.send(formData)
		// 监听响应
		xhr.onload = function(){
			if(xhr.status == 200){
				let param = xhr.response;
				if(param){
					$('#textContent').val(JSON.parse(param).data);
				}
			}
		}
		var input = event.target;
		var reader = new FileReader();
		reader.onload = function() {
			if(reader.result) {
				//显示文件内容
				//$("#output").html(reader.result);
				$('#audioIdPath').val(reader.result)
			}
		};
		reader.readAsText(input.files[0]);
	};
	//监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
	window.onbeforeunload = function () {
	  closeWebSocket();
	  //logout();
	}

	function send(msg){
		var message;
		var phonesel=$("input[name='phonesel']:checked").val();//控制话机1左2右
		if (method == 'call' || method == 'monitor' || method == 'bargein' || method == 'transfer' || method == 'transferask' || method == 'secret') {
			callOut = true
		}
		if(msg!=""&&typeof(msg)!="undefined"){
			message = "{'host':'"+host+"','method':'"+method+"','username':'"+username+"','password':'"+password+"','exten':'"+exten+"','pstnnumber':'"+pstnnumber+"','caller':'"+caller+"','callee':'"+callee+"','sys_user_id':'"+sysUserId+"','phonesel':'"+phonesel+"',"+msg+"}";
		} else{
			message = "{'host':'"+host+"','method':'"+method+"','username':'"+username+"','password':'"+password+"','exten':'"+exten+"','pstnnumber':'"+pstnnumber+"','caller':'"+caller+"','callee':'"+callee+"','sys_user_id':'"+sysUserId+"','phonesel':'"+phonesel+"'}";
		}
		websocket.send(message);
	}

	//关闭WebSocket连接
	function closeWebSocket() {
	    websocket.close();
		clearInterval(timeId);
		clearInterval(timeOne);
		if(timerInterval != null){
			clearInterval(timerInterval);
		}
	}
	function  login(){
	    method = "login";
	    send();
	}
	function  logout(){
	    method = "logout";
	    send();
	    if(heartbeatId>=0){
			clearInterval(heartbeatId);
		}
		localStorage.removeItem('rh_username')
		localStorage.removeItem('rh_password')
		localStorage.removeItem('rh_ip')
		localStorage.removeItem('rh_registerSIP')
		localStorage.removeItem('rh_token')
		// window.location.href=path+"/main.html"
	}
	
		
		
	//响应事件
	function onEvent(eventType,methodType,jsonStr){
		//console.log('==onEvent==', ' --eventType:', eventType, ' --methodType:', methodType, jsonStr)
		if(eventType=='event')//事件
		{

			if(methodType=='get_ext_status')//获取分机状态
			{
				return;
				for(var i=0;i<jsonStr.extens.exten.length;i++)
				{
				 $("#"+jsonStr.extens.exten[i].number+"state").html(jsonStr.extens.exten[i].status);
				}


			}else if(methodType=='ring')
			{//振铃
				var phonenum=jsonStr.ExtenInfo.split("@")[0];
				var loadExten = jsonStr.displayNum
				var _confName = jsonStr.confName
				var _appKey = jsonStr.appKey
				conferenceMemberChange(_confName, phonenum, _appKey, '', 'ring')
				 $("#s"+phonenum+"").html(getState("Ringing"));
				 $("#hc"+phonenum+"").attr("class",getStateClass("Ringing"));
				 $("#y"+phonenum+"").html(getState("Ringing"));
				 $("#hy"+phonenum+"").attr("class",getStateClass("Ringing"));
					if(phonenum==caller)//设置左右分机状态
		    		{
		    			setExtenLR(1,caller,"Ringing");
						if (register) {
							videoExten = phonenum
							if (!autoCall) {
								//显示弹窗
								$('#sipModal').modal('show')
								if (callOut) {
									comExten = phonenum
								} else {
									comExten = jsonStr.displayNum
								}
								for (var i = 0; i < listData.length; i++) {
									var ex = listData[i]
									var exten = ex.exten
									var position = ex.position
									if (ex.exten.indexOf('@') > -1) {
										exten = ex.exten.split('@')[0]
									}
									if (exten == comExten) {
										extenName = ex.employeename
										if (ex.position.indexOf(':') > -1) {
											position = ex.position.split(':')[0]
										}
										if (position == '' || position == null || position == undefined) {
											position = '未知'
										}
										extenIP = position
										break
									}
								}
								extenStatus = '振铃'
								setSipContent()
							}else {
								if (acceptModal=='video') {
									myWebrtc.VoiceAnsWter(true)
								}else if (acceptModal == 'audio'){
									myWebrtc.VoiceAnsWter(false)
								}
								
							}
						}
		    		}
		    		else if(phonenum==callee)
		    		{
		    			setExtenLR(2,callee,"Ringing");
		    		}
					var date = new Date();
					var time = date.toLocaleTimeString();
					updateStatus(phonenum,'Ringing')
					
					if ((phonenum===callee || phonenum === caller)&&(loadExten!==callee&&loadExten!==caller)) {
						loadRtmps(loadExten)
					}
				if (jsonStr.displayNum != phonenum) {
					if (callOut) {
						$('.call-info').prepend('<p>' + time + ':' + phonenum + '呼叫了' + jsonStr.displayNum + '</p>')
					} else {
						$('.call-info').prepend('<p>' + time + ':' + jsonStr.displayNum + '呼叫了' + phonenum + '</p>')
					}
				}
				callOut = false
			}
			else if(methodType=='answer')//应答
			{

				var phonenum=jsonStr.ExtenInfo.split("@")[0];
				var _appKey = jsonStr.appKey
				conferenceMemberChange('', phonenum, _appKey, '', 'talk')

				 $("#s"+phonenum+"").html(getState("Talking"));
				 $("#hc"+phonenum+"").attr("class",getStateClass("Talking"));

				 $("#y"+phonenum+"").html(getState("Talking"));
				 $("#hy"+phonenum+"").attr("class",getStateClass("Talking"));
					if(phonenum==caller)//设置左右分机状态
		    		{
		    			setExtenLR(1,caller,"Talking");
		    		}
		    		else if(phonenum==callee)
		    		{
		    			setExtenLR(2,callee,"Talking");
		    		}

					var date = new Date();
					var time = date.toLocaleTimeString();

					updateStatus(jsonStr.ExtenInfo,'Talking')

				if (jsonStr.displayNum != phonenum) {
					$('.call-info').prepend("<p>"+time+":"+phonenum+"与"+jsonStr.displayNum+"通话"+"</p>")
				}

			}
			else if(methodType=='broading')
			{
				//广播
				var phonenum=jsonStr.ExtenInfo.split("@")[0];

				conferenceMemberChange('', phonenum, '', '', 'broad')

				$("#s"+phonenum+"").html(getState("Broading"));
				$("#hc"+phonenum+"").attr("class",getStateClass("Broading"));

				$("#y"+phonenum+"").html(getState("Broading"));
				$("#hy"+phonenum+"").attr("class",getStateClass("Broading"));
				//设置左右分机状态
				if(phonenum==caller){
					setExtenLR(1,caller,"Broading");
				}
				else if(phonenum==callee){
					setExtenLR(2,callee,"Broading");
				}
				var date = new Date();
				var time = date.toLocaleTimeString();
				updateStatus(jsonStr.ExtenInfo,'Broading')
				if (jsonStr.displayNum != phonenum) {
					$('.call-info').prepend("<p>"+time+":"+phonenum+"与"+jsonStr.displayNum+"通话"+"</p>")
				}
			}else if("Bridge" == methodType)
			{//接通
				var phonenum=jsonStr.ExtenInfo_b;
				let is_Broadcast = statusList.find(item=>item.exten.split("@")[0] == phonenum && "Broading" == item.status);
				if(is_Broadcast){
					$("#s"+phonenum+"").html(getState("Talking"));
					$("#hc"+phonenum+"").attr("class",getStateClass("Talking"));

					$("#y"+phonenum+"").html(getState("Talking"));
					$("#hy"+phonenum+"").attr("class",getStateClass("Talking"));
					//设置左右分机状态
					if(phonenum==caller){
						setExtenLR(1,caller,"Talking");
					}
					else if(phonenum==callee){
						setExtenLR(2,callee,"Talking");
					}
					var date = new Date();
					var time = date.toLocaleTimeString();
					updateStatus(phonenum,'Talking')
				}
			}else if(methodType=='handup')//挂机
			{
				var phonenum=jsonStr.ExtenInfo.split("@")[0];

				var _appKey = jsonStr.appKey
				conferenceMemberChange('', phonenum, _appKey, '', 'hangup')

				if(jsonStr.ExtenInfo.indexOf("@")!=-1){

				 $("#s"+phonenum+"").html(getState("Idle"));
				 $("#hc"+phonenum+"").attr("class",getStateClass("Idle"));
				 $("#y"+phonenum+"").html(getState("Idle"));
				 $("#hy"+phonenum+"").attr("class",getStateClass("Idle"));
				}
				 else
				 {
					 $("#s"+phonenum+"").html("未知");
					 $("#hc"+phonenum+"").attr("class","panel panel-warning");
					 $("#y"+phonenum+"").html("未知");
					 $("#hy"+phonenum+"").attr("class","panel panel-warning");


					 //外线移除一个状态数据
					 //removeStatusListJson(phonenum,'Ringing')
				 }
				if(phonenum==caller)//设置左右分机状态
	    		{
	    			setExtenLR(1,caller,"Idle");
					if (register) {
						$('#sipModal').modal('hide')
					}
	    		}
	    		else if(phonenum==callee)
	    		{
	    			setExtenLR(2,callee,"Idle");
	    		}

				var date = new Date();
				var time = date.toLocaleTimeString();
				if (jsonStr.displayNum !== null && phonenum !== null && jsonStr.displayNum !== 'null' && phonenum !== 'null') {
					if(jsonStr.displayNum!=phonenum){
						$('.call-info').prepend("<p>"+time+":"+phonenum+"挂断了"+jsonStr.displayNum+"</p>")
					}
				}
				
				updateStatus(jsonStr.ExtenInfo,'Idle')


				//从所有会议中循环出分机,移除
				if(conf_status.length > 0){
					for(let i = 0; i < conf_status.length; i++){
						var exs = conf_status[i]
						var exts = []
						for(let j = 0; j < exs.extens.length; j++){
							let ex = exs.extens[j].split('@')[0]
							if(ex != phonenum){
								exts.push(ex)
							}else {
								removeInconfExten(ex)
								exs.inConfNum = exs.inConfNum - 1
								if(exs.confname == confname){
									if(exs.isName == '0'){
										let data = getDataByConfName(confname)
										let exjson = getExtenJson(exts,data)
										data = data.concat(exjson)
										loadConfrenceExten(data)
										//移除静音成员
										removeMuteExten(confname,phonenum)
										changeMul(confname)
										isName = 0
									}else {
										var all = []
										let exjson2 = getExtenJson(exts,all)
										loadConfrenceExten(exjson2)
										changeMul(confname)
										isName = 1
									}
								}
								if(exs.inConfNum <= 0){
									conferencecloseNoTip(exs.confname)

								}
							}
						}
						conf_status[i].extens = exts
					}
				}
			}
			else if(methodType=='online')//分机上线
			{

				var phonenum=jsonStr.ExtenInfo.split("@")[0];
				conferenceMemberChange('', phonenum, '', '', 'idle')
				 $("#s"+phonenum+"").html(getState("Idle"));
				 $("#hc"+phonenum+"").attr("class",getStateClass("Idle"));
				 $("#y"+phonenum+"").html(getState("Idle"));
				 $("#hy"+phonenum+"").attr("class",getStateClass("Idle"));
					if(phonenum==caller)//设置左右分机状态
		    		{
		    			setExtenLR(1,caller,"Idle");
		    		}
		    		else if(phonenum==callee)
		    		{
		    			setExtenLR(2,callee,"Idle");
		    		}
					updateStatus(jsonStr.ExtenInfo,'Idle')
					
			}
			else if(methodType=='offline')//分机下线
			{

				var phonenum=jsonStr.ExtenInfo.split("@")[0];

				conferenceMemberChange('', phonenum, '', '', 'offline')
				 $("#s"+phonenum+"").html(getState("OffLine"));
				 $("#hc"+phonenum+"").attr("class",getStateClass("OffLine"));
				 $("#y"+phonenum+"").html(getState("Idle"));
				 $("#hy"+phonenum+"").attr("class",getStateClass("Idle"));
					if(phonenum==caller)//设置左右分机状态
		    		{
		    			setExtenLR(1,caller,"Idle");
		    		}
		    		else if(phonenum==callee)
		    		{
		    			setExtenLR(2,callee,"Idle");
		    		}
					updateStatus(jsonStr.ExtenInfo,'OffLine')
			}
			else if(methodType=='alarm')//报警
			{

				var phonenum=jsonStr.ExtenInfo.split("@")[0];
				$("#s"+phonenum+"").html(getState("alarm"));
				$("#hc"+phonenum+"").attr("class",getStateClass("Ringing"));
				$("#y"+phonenum+"").html(getState("alarm"));
				$("#hy"+phonenum+"").attr("class",getStateClass("Ringing"));
				var data = getAlarmDetail(jsonStr.id)
				if(data == ""){
					$.alert('获取报警数据错误')
					return
				}
				$.confirm({
					title:'',
					content:phonenum+'报警',
					buttons:{
					    处理:function(){
							alarm_recover(data[0].id,data[0].device_no,data[0].profile,data[0].alarm_data)
							var alarm = getAlarmDetail(data[0].id)
							if (alarm) {
								var ala = {
									id:alarm.id,
									deviceNo:alarm.device_no,
									deviceName:alarm.device_name,
									alarm_level:alarm.alarm_level,
									alarmData:alarm.alarm_data,
									remarks:alarm.remarks
								}
								openAlarmModel(ala)
							}

					    },
					    忽略: function(){
							alarm_recover(data[0].id,data[0].device_no,data[0].profile,data[0].alarm_data)
					    }
					}

				})

			}else if(methodType=='getconferencelist'){//会议
				confList = jsonStr.confInfos
				//gd_conf = getGDConf()
				//diffConf(confList)
				generatorConference(confList, false)
			}
			else if(methodType == 'LeaveConferce')
			{
				var phonenum=jsonStr.ExtenInfo.split("@")[0];
				//移除一个分机
				//removeInconfExten(phonenum)
				var _appKey = jsonStr.appKey
				var _confName = jsonStr.confname
				var _name = jsonStr.ExtenName
				!_name ? _name = phonenum : null
				conferenceMemberChange(_confName, phonenum, _appKey, _name, 'leave')

				updateStatus(jsonStr.ExtenInfo,'Idle')

			}
			else if(methodType == 'EnterConference')
			{
				//判断是否是用户呼入开始会议
				//isOpenConf(jsonStr)
				var phonenum=jsonStr.ExtenInfo.split("@")[0];
				var _appKey = jsonStr.appKey
				var _confName = jsonStr.confname
				var _name = jsonStr.ExtenName
				!_name ? _name = phonenum : null
				conferenceMemberChange(_confName, phonenum, _appKey, _name, 'enter')

				updateStatus(jsonStr.ExtenInfo,'Talking')
				 $("#s"+phonenum+"").html(getState("Talking"));
				 $("#hc"+phonenum+"").attr("class",getStateClass("Talking"));

				 $("#y"+phonenum+"").html(getState("Talking"));
				 $('#i'+phonenum).removeClass('glyphicon-user')
				 $('#i'+phonenum).addClass('glyphicon-earphone')
					if(phonenum==caller)//设置左右分机状态
					{
						setExtenLR(1,caller,"Talking");
					}
					else if(phonenum==callee)
					{
						setExtenLR(2,callee,"Talking");
					}

				if(phonenum==caller)//设置左右分机状态
				{
					setExtenLR(1,caller,"Talking");
				}
				else if(phonenum==callee)
				{
					setExtenLR(2,callee,"Talking");
				}


			}
			else if (methodType == 'MuteConference') {
				var _appKey = jsonStr.appKey
				var phonenum = jsonStr.ExtenInfo.split('@')[0]
				var _confName = jsonStr.confname
				conferenceMemberChange(_confName,phonenum,_appKey,'','mute')
			} else if(methodType == 'CancelMuteConference'){
				var _appKey = jsonStr.appKey
				var phonenum = jsonStr.ExtenInfo.split('@')[0]
				var _confName = jsonStr.confname
				conferenceMemberChange(_confName,phonenum,_appKey,'','unmute')
			}else if(methodType == 'videoConferenceInvite'){
				// todo conference 弹屏邀请
				videoConfInvite(jsonStr)
				createAndShowVmInviteModal(jsonStr)
			}
			else if(methodType == 'vcsReject'){
				// todo conference 拒绝邀请
				videoConfReject(jsonStr)
			}
			else if (methodType == 'enterqueue') {
				var queuename = jsonStr.queuename
				var phonenum = jsonStr.ExtenInfo
				var date = new Date()
				var time = date.toLocaleTimeString()
				$('.queue-info').prepend('<p>' + time + ':' + phonenum + '进了队列' + queuename + '</p>')
			} else if (methodType == 'leavequeue') {
				var phonenum = jsonStr.ExtenInfo
				var date = new Date()
				var time = date.toLocaleTimeString()
				$('.queue-info').prepend('<p>' + time + ':' + phonenum + '离开队列</p>')
			} else if (methodType == 'BroadcastStart') {
				sleep(1000)
				//生成表格
				generTaskTable()
			} else if (methodType == 'BroadcastStop') {
				sleep(1000)
				//刷新表格
				$('.tow_nav').html(svalue)
				//生成表格
				generTaskTable()
			} else if (methodType == 'preplan_start') {
				loadActionPlanTable()
			}
		}
		else if(eventType=='response')//请求响应
		{
			var retcode=jsonStr.retCode;

			 if(methodType=='HeatBeat')
			{//心跳检测
				if(retcode=='0'){
					loseHeartbeat = 0;

				}
			}
			 else if(methodType=='logindata')
				{    //登录返回
					if(retcode!='0')
					{
						$.alert(jsonStr.reason);
					}
					else
					{
						if(heartbeatId>=0){
							clearInterval(heartbeatId);
						}
							userId = jsonStr.sys_user_id;
							heartbeatId = setInterval("heartbeat()",timeoutSec*1000);//心跳
							listData = [].concat(jsonStr.contact);
							current_areaExtens = [].concat(jsonStr.contact)
							leftMenuForControl = getLeftMeanData();
							let newParam = JSON.parse(JSON.stringify(leftMenuForControl))
							newParam = getDeptAllData(newParam);
							let param = {text:'仅管理员可见',id:'-1',nodeId:'-1'}
							if(newParam[0]){
								newParam[0].id = '-2';
							}
							if('1' == isAdmin){
								newParam[0].nodes.unshift(param);
							}
							allDeptData = newParam;
							if('0' == isAdmin && deptId){
								allDeptData = newParam[0].nodes;
							}
							setAllDeptList(allDeptData);
						    firstLoad=1;
							//setTimeout(getconferencelist(),30000);//加载会议
							caller=jsonStr.leftexten.split("@")[0];
							callee=jsonStr.rightexten.split("@")[0];
							//不在发送getextstatus命令，由后台直接传递在进行排序
							sortAndInitControl(jsonStr.contact);
							if(caller == '' || caller == null || caller == 'null'){
								displayCall(1)
							}
							if(callee == '' || callee == null || callee == 'null'){
								displayCall(2)
							}
							sendNotice();
							displaynum = jsonStr.display_num

					}
				}
			 

			else if(methodType=='UserBroadcastSetVol')//设置广播声音
			{
				if(retcode!='0'){//出错
					$.alert(jsonStr.reason);
				}else{
					//不做处理
				}
			}else if(methodType=='UserBroadcastStart'){
				if(retcode != '0'){
					$.alert(jsonStr.reason)
					return;
				}else{
					//刷新表格
					$(".tow_nav").html(svalue)
					//生成表格
					generTaskTable()
				}

			}else if(methodType == 'UserBroadcastStop'){
				if(retcode != '0'){
					$.alert(jsonStr.reason)
					return;
				}else{
					sleep(1000)
					//刷新表格
					$(".tow_nav").html(svalue)
					//生成表格
					generTaskTable()
				}

			}else if(methodType == 'UserThreeway_Conferce'){
				
			}
			else if(methodType=='broadcast_stop')//停止广播
			{
				if(retcode!='0'){
					$.alert(jsonStr.reason);
					return;
				}
			}else if(methodType=='UserKickConference'){

			}else if(methodType == 'UserMuteConference'){

			}else if(methodType == 'UserDeafConference'){
				
			}else if(methodType == 'UserCancelDeafConferce'){
				
			}else if(methodType == 'UserJoinConference'){
				
			}else if(methodType == 'UserCreateStaticConference'){

			}else if (methodType == 'kick') {
				setTimeout(function(){
					localStorage.removeItem('rh_username')
					localStorage.removeItem('rh_password')
					localStorage.removeItem('rh_ip')
					localStorage.removeItem('rh_registerSIP')
					// window.location.href=path+"/main.html"
				},2000)
			 }else if(methodType == 'notice'){
				let data = jsonStr.data;
				 alertMessage(data);
			 }else if (methodType == 'invite') {
				 processInviteInfo(jsonStr)
			 }

		}
	}
	function sortAndInitControl(jsonStr) {
		statusList = jsonStr;
		var data = changeOrder(statusList,listData)
		/*var base = new Base64();
		var str = username+":"+password;
		var Authorization = base.encode(str)*/
		$.ajax({
			url:httpProto+'://'+host+'/control/api-v2.2.3/20211118/getDeptListByFatherId.json',
			//url:'http://localhost:8080/control/api-v2.2.3/20211118/getDeptListByFatherId.json',
			type:'post',
			data:JSON.stringify({"deptId":deptId,"isAdmin":isAdmin,"userDeptId":""}),
			dataType:'json',
			async:false,
			beforeSend:function(request){
				request.setRequestHeader("Authorization",localStorage.getItem('rh_token'))
			},
			contentType:'application/json',
			success:function(result){
				if (result.code === 200) {
					var newData = [];
					let arr = result.data[0];
					if(arr){
						arr = arr.split(",");
					}
					for(var i = 0; i < listData.length; i++){
						if(arr.indexOf(listData[i].dept_id) != -1 && listData[i].showControl === "1"){
							newData.push(listData[i])
						}
					}
					listData = newData
					LoadExtenList(newData);

					setExtenList(jsonStr);
					mapStatusList = jsonStr;
					/*if(fristLoad==0)
					{
						getconferencelist();
					}*/
				}
			}
		})
	}
	function displayCall(num){
		if(num == 1){
			$(".bleft").unbind('click')
			$("#lstate").html('离线')
		}else if(num == 2){
			$(".bright").unbind('click')
			$("#rstate").html('离线')
		}
	}

	/* 改变分机状态 */
	function updateStatus(phone,status){
		var num = phone.split('@')[0]
		if(phone.indexOf('@')== -1){
			//status = 'UnKnow'
			if(status == 'Idle' || status == 'OffLine'){
				//挂机 移除
				for(let i = statusList.length - 1; i >= 0; i--){
					if(statusList[i].number == num){
						statusList.splice(i,1)
					}
				}
			}else {
				//上线状态添加一个状态
				var f = true
				for(let i = 0; i < statusList.length; i++){
					if(statusList[i].number == num){
						statusList[i].status = status
						f = false
					}
				}
				if(f){
					var param = {'company_id':'','gid':'','gname':'','network':'null','number':num,'status':status}
					statusList.push(param)
				}
			}
		}
		//phone = phone.split('@')[0]
		if(statusList.length>0){
			for(let i = 0; i < statusList.length; i ++){
				if(statusList[i].number == num){
					statusList[i].status = status
				}
			}
		}
		//排序
		var data = changeOrder(statusList,listData)
		listData = data
		LoadExtenList(data);
		setExtenList(statusList)
		setMapExten(statusList);
		mapStatusList=statusList;
	}

	//处理分机排序
	function changeOrder(status,extens){
		if(status == null || extens == null){
			return
		}
		for (let i = 0; i < status.length; i++) {
			var sta = status[i]
			if(!sta.number){
				sta.number = sta.exten.split("@")[0];
			}
			for (let j = 0; j < extens.length; j++) {
				var ex = extens[j]
				var exten = ""
				if(ex.exten.indexOf('@')!=-1){
					exten = ex.exten.split('@')[0]
				}else{
					exten = ex.exten
					ex.order_list = 0
				}
				if(exten==sta.number){
					if(sta.status == 'Talking' || sta.status == 'Ringing'){
						ex.order_list = -4
					}else if (sta.status == 'Idle') {
						ex.order_list = -2
					}else if (sta.status == 'OffLine') {
						ex.order_list = -1
					}else if (sta.status == 'Broading') {
						ex.order_list = -3
					}
				}
			}
		}
		extens.sort(sortId)
		return extens
	}

	function sortId(a,b){
	    return a.order_list-b.order_list
	}
	//加载分机
	function  LoadExtenList(contacts){
		var extlength=contacts.length;
		var extHtml="";
		for(var i=0;i<extlength;i++){
			//判断内线
			if(contacts[i].exten.indexOf("@")!=-1){
				extHtml +="<div class='panel col-md-1' id=\"hc"+contacts[i].exten.split("@")[0]+"\">"
				extHtml+="<div class=\"panel-heading \" ><h6 class=\"panel-title font-weight-normal\" id=\"s"+contacts[i].exten.split("@")[0]+"\">离线</h6></div> ";

			}else{//外线
				extHtml +="<div class='panel col-md-1 panel-warning' id=\"hc"+contacts[i].exten.split("@")[0]+"\">"
				extHtml+="<div class=\"panel-heading \" ><h6 class=\"panel-title font-weight-normal\" id=\"s"+contacts[i].exten.split("@")[0]+"\">未知</h6></div> ";
			}
			extHtml += "<div class='panel-body'><ul class=\"list-unstyled\"><li>"+contacts[i].deptname+"</li><li><i class='glyphicon glyphicon-user'></i>"+contacts[i].employeename+"</li><li>"+contacts[i].exten.split('@')[0]+"</li></ul></div>"
			extHtml += "</div>";
		}

		$("#homeindex").html(extHtml);

		setTimeout( setExtenSelected(),3000)
		$('.panel').addClass('col-md-1');
	}

	function setExtenSelected(){
	        $("#homeindex .panel").click(function(){
				var phone = $(this).children(".panel-body").children().children("li").eq(2).html().split("@")[0];;
	            if($(this).hasClass('selected')){
					$(this).removeClass('selected')
					if(phoneList.indexOf(phone) > -1){
						phoneList.splice(phoneList.indexOf(phone),1)
					}
				}else{
					if($(this).children().children().html()!="离线"&&$(this).children().html()!=undefined){
						$(this).addClass("selected");
						phoneList.push(phone)
					}
				}
				if(phoneList.length == 1){
					$("#phone").val(phoneList[0])
					$(".selectphone-more").attr('hidden','true')
					$('.selectphone-one').removeAttr('hidden')
				} else if(phoneList.length == 0){
					$("#phone").val("")
					$(".selectphone-more").attr('hidden','true')
					$('.selectphone-one').removeAttr('hidden')
				}else if(phoneList.length > 1){
					$(".selectphone-one").attr('hidden','true')
					$('.selectphone-more').removeAttr('hidden')
				}
	        });
	}
	function selectphone(data){
		if(data==1){
			$(".bleft").addClass('phone-selected')
			$(".bright").removeClass('phone-selected');
			$('#leftphone').prop('checked','true')
			$('#controlSIP').html("控制分机:"+caller)
		}else{
			$('.bleft').removeClass('phone-selected')
			$('.bright').addClass('phone-selected')
			$('#rightphone').prop('checked','true')
			$('#controlSIP').html("控制分机:"+callee)
		}
	}


	//设置左右分机状态
	function setExtenLR(index,ext,state){

		if(index==1){
			 $(".bleft").addClass("phone-selected")
			 $(".bright").removeClass("phone-selected")
			 $("#leftphone").removeAttr("disabled")
			 $('#controlSIP').html("控制分机:"+caller)
			 if(state=="OffLine"){
				 $("#leftphone").attr("disabled","disabled");
				 $(".bleft").unbind('click');
				 $("#lstate").html(getState(state));
				 $(".bleft").removeClass("phone-selected")
				 $(".bright").addClass("phone-selected")
				 //添加离线样式

				 $("#rightphone").prop("checked","true");
				 $('#controlSIP').html("控制分机:"+callee)
			 }else{
				 $("#leftphone").prop("checked","true");
				 $(".bleft").unbind('click')
				 $(".bleft").click(function(){
					 selectphone(1)
					//记录用户选中状态
					isRightCall = false;
					//console.log("click left.....")
				 })
				 var stateName = getState(state);
			 }

		}else{
			 $(".bright").addClass("phone-selected")
			 $(".bleft").removeClass("phone-selected")
			 $("#rightphone").removeAttr("disabled")
			 $('#controlSIP').html("控制分机:"+callee)
			 if(state=="OffLine"){
				 $("#rightphone").attr("disabled","disabled");
				 $(".bright").unbind('click')
				 $("#rstate").html(getState(state))
				 $(".bright").removeClass("phone-selected")
				 $(".bleft").addClass("phone-selected")
				 $("#leftphone").prop("checked","true");
				 $('#controlSIP').html("控制分机:"+caller)
			 }else{
				//if(!$("#leftphone").attr("checked")){
				 $('#rightphone').prop('checked','true')
				 $(".bright").unbind('click')
				 $('.bright').click(function(){
					selectphone(2)
					//记录用户选中状态
					isRightCall = true;
					//console.log("click right.....")
				 })
				 var stateName = getState(state);
		    }
		}

		//默认选中左分机，防止右分机覆盖了左分机
		selectphone(1);

		//如果用户手动选择右话机，则切换至右话机
		if(isRightCall){
			selectphone(2);	
			//console.log("用户手动选择了右分机");
		}


	}

	//设置分机状态
	function setExtenList(extens){

		var extlength=extens.length;
		for(var i=0;i<extlength;i++){
			let number = extens[i].exten ? extens[i].exten.split("@")[0]+"" : extens[i].number+"";
			$("#hc"+number+"").addClass(getStateClass(extens[i].status));
			$("#s"+number+"").html(getState(extens[i].status));
			if(number==caller)//设置左右分机状态
			{
				setExtenLR(1,caller,extens[i].status);
			}
			else if(extens[i].exten==callee)
			{
				setExtenLR(2,callee,extens[i].status);
			}
		}
		var other = []
		for(let i = 0; i < listData.length; i++){
			if(listData[i].exten.indexOf('@')==-1){
				other.push(listData[i].exten)
			}
		}
		if(other.length > 0){
			for(let i = 0; i < other.length; i++){
				$("#hc"+other[i]+"").addClass(" panel-warning")
			}
		}

	}

	function getState(state){

	 	var c=" ";
		switch(state)
		{
		case  "Idle": c="空闲";break;
		case  "Ringing": c="振铃";break;
		case "Talking": c="通话";break;
		case "Broading": c="广播";break;
		case "OffLine": c="离线";break;
		case "UnKnow": c="未知";break;
		case "UnKnown": c="未知";break;
		default:c="离线";

		}
		return c;

	}

	function getStateClass(state){
		var c="panel ";
		switch(state)
		{
		case  "Idle": c+="col-md-1 panel-primary";break;
		case  "Ringing": c+="col-md-1 panel-danger";break;
		case "Talking": c+="col-md-1 panel-success";break;
		case "Broading": c+="col-md-1 panel-info";break;
		case "OffLine": c+="col-md-1 panel-default";break;
		case "UnKnow": c+="col-md-1 panel-warning";break;
		case "UnKnown": c+="col-md-1 panel-warning";break;
		default:c="col-md-1  panel-default";

		}
		return c;

	}

	//心跳检测
	function heartbeat(){
		if(loseHeartbeat>=3){//丢3次重新登陆
			if(heartbeatId>=0){
				clearInterval(heartbeatId);
			}
			uni.showToast({
				title: '与服务器连接中断，请重新登录',
				icon: 'error'
			})
		}else{
			loseHeartbeat = loseHeartbeat+1;

			method = "heartbeat";
	  		send();
		}
	}
	function sendNotice() {
		method = "notice";
		send();
	}
	//呼叫
	function call(){
	    exten =  $("#phone").val();
		if(exten!=""){
	    	 method = "call";
	    	 send();
	    } else{
			$.alert("请选择分机")
		}
	}
	//挂断
	function handup(){
		exten =  $("#phone").val();
		if(exten!="")
		{
	    method = "handup";
	    send();
	    }
	}

	 //监听
	 function monitor(){
		 exten =  $("#phone").val();
	 	if(exten!="")
		{

		 method = "monitor";
		 send();
		 }
	 }

	 //强插
	 function bargein(){

		 exten =  $("#phone").val();
	  	if(exten!="")
	 	{
	 	 method = "bargein";
	 	 send();
	 	 }

	 }

	 //拆讲
	 function transfer(){

		 exten =  $("#phone").val();
	  	if(exten!="")
	 	{
	 	 method = "transfer";
	 	 send();
	 	 }

	 }

	 //转接
	 function transferask(){

		 exten =  $("#phone").val();
	  	if(exten!="")
	 	{
	 	 method = "transferask";
	 	 send();
	 	 }

	 }
	 //密语
	 function secret(){

		 exten =  $("#phone").val();
	  	if(exten!="")
	 	{
	 	 method = "secret";
	 	 send();
	 	 }

	 }

	 function queueanswer(){
		 exten =  $("#phone").val();
		  var queuename="";
		  var queueid="";
		 var msgtxt="'queuename':'"+exten+"','queueid':'"+queueid+"'";//当前分机的呼叫组名称



	   	if(exten!="")
	  	{
	  	 method = "queueanswer";
	  	 send(msgtxt);
	  	 }
	 }
	function getLeftMeanData(){
		// var base = new Base64();
		// var extenArr = [];
		// var str = username+":"+password;
		// var Authorization = base.encode(str)
		$.ajax({
			url:httpProto+"://"+host+"/control/api-v2.2.3/getDeptListById.json",
			type: "get",
			data:{"user_id":userId},
			async:false,
			beforeSend:function(request){
				request.setRequestHeader("Authorization",localStorage.getItem('rh_token'))
			},
			contentType:"application/json",
			success:function(res){
				if (res.statuscode === '000000') {
					let trrDate = res.data;
					if(trrDate && trrDate.length > 0){
						trrDate = JSON.parse(JSON.stringify(trrDate).replace(/"name":/g,"\"text\":").replace(/"children":/g,"\"nodes\":"));
					}
					let total = 0;
					let online = 0;
					let item = res.data;
					//获取全部区域的在线总数、终端总数
					for (let i = 0; i < item.length; i++) {
						let newTotal = parseInt(item[i].total) ? parseInt(item[i].total) : 0
						total = total+newTotal;
						newTotal = parseInt(item[i].online) ? parseInt(item[i].online) : 0;
						online = online+newTotal;
					}
					let params = [{
						id:'',
						pId:'',
						text:"全部区域",
						nodes:trrDate,
						tags: [""+online+"/"+total+""]
					}];
					extenArr = params;
				}
			}
		})

		return extenArr;
	}
	function getDeptAllData(moduleDataList) {
		for (let i = 0; i < moduleDataList.length; i++) {
			if(deptId == moduleDataList[i].id){
				deptIdName = moduleDataList[i].text;
			}
			moduleDataList[i].nodeId = moduleDataList[i].id;
			if (moduleDataList[i].nodes) {
				moduleDataList[i].nodes = getDeptAllData(moduleDataList[i].nodes);
			}
		}
		return moduleDataList
	}
	
	function offLineNum(arr){
		if(arr.length < 0 || inlineList.length < 0){
			return 0;
		}
		//获取全部的离线分机
		var i = 0;
		for(var i = 0; i < arr.length; i++){
			var ex = arr[i].exten.split("@")[0]
			for(var j = 0; j < inlineList.length; j++){
				if(inlineList[j].number == ex){
					i += 1;
				}
			}
		}
		return i;
	}
	var current_deptId = '0'
	var current_deptName = '全部区域'
	var current_areaExtens = [];//分区成员,默认全部

	/* 广播部分 */
	var stype = "";
	var svalue = "";
	function loadBroadLeftTable(){
		var taskList = [{id:'0',name:'全部任务'},
					{id:'1',name:'音乐任务'},
					{id:'2',name:'喊话任务'},
					{id:'3',name:'文字任务'},
					{id:'4',name:'采播任务'},
					// {id:'5',name:'文件任务'},
					{id:'6',name:'离线任务'}]
		$("#procitytree").hide();
		$("#treetable").bootstrapTable('destroy')
		$("#treetable").bootstrapTable({
			cache:false,
			data:taskList,
			clickToSelect:true,
			uniqueId:'id',
			showColumns: false,
			scrollbar:true,
			columns:[{
				field:'name',
				formatter:function(value,item,index){

					var html = "<label class='glyphicon glyphicon-flash'></label>"+value;
					return html;

				}
			}],
			onClickCell:function(field,value,row,$element){
				$(".tow_nav").html(value)
				var type = "";
				$('.btn-gb').removeAttr('hidden')
				$('.btn-gb-offline').attr('hidden','hidden')

				$('#offLineActiveState').hide()
				$('#searchPlayType').show()
				$('#activeState').show()
				$('#searchEnable').show()
				if(value=='全部任务'){
					type=""
				}else if(value == '音乐任务'){
					type='2'
				}else if(value == '文字任务'){
					type='1'
				}else if(value == '喊话任务'){
					type = '4'
				}else if(value == '采播任务'){
					type = '5'
				}else if(value == '离线任务'){
					//离线任务将搜索栏一些隐藏。
					$('#searchPlayType').hide()
					$('#searchEnable').hide()
					$('#offLineActiveState').show()
					$('#activeState').hide()

					type = '6'
					$('.btn-gb-offline').removeAttr('hidden')
					$('.btn-gb').attr('hidden','hidden')
				}
				stype = type;
				svalue = value;
				//生成表格
				generTaskTable()
			}
		})
	}
	/* 生成表格 */
	function generTaskTable(){
		let column = [{
			checkbox:true
		},{
			field:'name',
			title:'名称'
		},{
			field:'access_num',
			title:'接入号'
		},{
			field:'status',
			title:'激活状态',
		},{
			field:'play_type',
			title:'播放类型',
		},{
			field:'type',
			title:'广播类型',
		},{
			field:'ptime',
			title:'播放时间'
		},{
			field:'playing_mode',
			title:'播放模式'
		},{
			field:'priority',
			title:'优先级'
		},{
			field:'prompt_tone',
			title:'提示音'
		},{
			field:'volume',
			title:'音量'
		},{
			field:'b_enable',
			title:'是否启用'
		},]
		if("6" == stype){
			column = [{
				checkbox:true
			},{
				field:'name',
				title:'名称'
			},{
				field:'status',
				title:'状态'
			},{
				field:'type',
				title:'类型',
			},{
				field:'ptime',
				title:'播放时间',
			}];
		}
		$('#broadtable').bootstrapTable('destroy')
		$('#broadtable').bootstrapTable({
			cache:false,
			data:'',
			type: "6" == stype ? "Get":"Post",
			ajax:loadBroadTaskData,
			clickToSelect:true,
			uniqueId:'id',
			showColumns:false,
			scrollbar:true,
			search:false,
			height:'500px',
			autoHeight: true,
			columns:column,
			queryParams : function (params) {
			 	//这里的是搜索条件
				let temp = {
					type:stype,//对应页面左侧列表的类型
					userId:userId,
					name:$("#broadName").val(),//广播名称
					bEnable:$('#searchEnable option:selected').val(),//是否启用
					priority:"",//优先级 1-高 4-中 5-低
					compareVolume:"",//音量值的运算符，>、<、=、<=、=>
					volume:"",//音量值
					playType: $('#searchPlayType option:selected').val(),//播放类型
					status: $('#activeState option:selected').val(),//激活状态
					currPage:(params.offset / params.limit) + 1,
					pageLimit:params.limit,
					properties:params.sort,
					direction:params.order,
				};
				if("6" == stype){
					temp.bEnable = "";
					temp.status = $('#offLineActiveState option:selected').val(),//激活状态;
					temp.playType = "";
				}
				return temp;
			},
			pagination:true,
			pageNumber:1,
			sidePagination:'server',
			pageSize:10,
			pageList:[10, 20, 50, 100],

		})
		var contentHeight = getVisible();
		var toolBarH = $('.fixed-table-toolbar').height();
		var height = contentHeight - toolBarH -131;
		var container = $('.fixed-table-container').css({'height':height})
	}
	/* 获取content 可见高度 */
	function getVisible() {
	    var $el = $('.content'),
	        scrollTop = $(this).scrollTop(),
	        scrollBot = scrollTop + $(this).height(),
	        elTop = $el.offset().top,
	        elBottom = elTop + $el.outerHeight(),
	        visibleTop = elTop < scrollTop ? scrollTop : elTop,
	        visibleBottom = elBottom > scrollBot ? scrollBot : elBottom;
		var bu = $('.mb').height() + $('.footer').height() + 80
		var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;   //height
		var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
		//return visibleBottom - visibleTop -bu
	    return h - visibleTop - bu;
	}

	/* 处理数据 */
	function processBroadData(data){
		if(data.length<0){
			console.log("无数据!")
		}
		let k = -1
		for(var i = 0; i < data.length; i++){
			var broad = data[i]
			if(broad.priority+''==='1'){
				k = i
			}
			broad.priority = getPriorityTxt(broad.priority+'')
			broad.play_type = getPlayTypeTxt(broad.playType+'')
			broad.b_enable = getB_enableTxt(broad.bEnable+'')
			broad.volume = broad.volume-5;
			broad.id = broad.id+'';

			broad.timetype = ''
			broad.ptime = ''
			if(broad.broadcastTimes && broad.broadcastTimes[0]){
				broad.timetype = broad.broadcastTimes[0].timeType+''
				broad.ptime = broad.broadcastTimes[0].playingTime+''
				if('2' == broad.timetype){
					let timeList = [];
					broad.broadcastTimes.forEach(newItem => {
						let paramNew = {
							"week_day":newItem.weekDay+"",
							"week_time":newItem.weekTime+"",
						}
						timeList.push(paramNew);
					})
					broad.ptime = timeList
				}
			}
			if("6" != broad.type+''){
				allAudioList.forEach(newItem => {
					if(newItem.id == broad.promptTone+''){
						broad.prompt_tone = newItem.audio_name;
					}
				})
			}
			if(!broad.ptime){
				broad.ptime = broad.createDate+''
			}
			if(broad.timetype == '2'){
				broad.ptime = getTimeName(broad.ptime)
			}
			broad.status = "6" == broad.type+'' ? getOfflineStatusText(broad.status+'') : getStatusTxt(broad.status+'')
			broad.type = getTypeTxt(broad.type+'')
			broad.playing_mode = getPlayModeTxt(broad.playingMode+'')
			broad.access_num = broad.accessNum+"";
		}
		if (k>-1) {
			data.splice(k,1)
		}
	}
	function getOfflineTime(arr) {
		let str = "";
		for (let j = 0; j < arr.length; j++) {
			switch (arr[j].week_day) {
				case "6":
					str += "每周日、"
					break
				case "0":
					str += "每周一、"
					break
				case "1":
					str += "每周二、"
					break
				case "2":
					str += "每周三、"
					break
				case "3":
					str += "每周四、"
					break
				case "4":
					str += "每周五、"
					break
				case "5":
					str += "每周六、"
					break
			}
		}
		return str;
	}
	/* 获取元数据 */
	function loadBroadTaskData(request){
		var data = [];
		let url = httpProto+"://"+host+"/control/api_v2.2.5/broad/query/all.json";
		if("6" == stype){
			url = httpProto+"://"+host+"/control/api_v2.2.5/broad/query/queryOffLineAll.json";
		}
		$.ajax({
			// type: "6" == stype ? "Get":"Post",
			type: "Get",
			url: url,
			data:request.data,
			contentType:"application/json",
			async:false,
			headers:{
				'Authorization':authForAll,
			},
			success: function(jsonStr){
				if(jsonStr.code == 200){
					data = jsonStr.data
				}
				//处理数据
				processBroadData(data.list)
				request.success({
					total: data.totalCount,
					rows: data.list
				})
			},
			error:function(){
				$.alert('查询出错!');
			}
		});
	}
	function  getPlayModeTxt( mode){
	    //1:顺序 2：随机 3：循环
	    var ret_mode = "";
	    switch (mode)
	    {
	        case "1":
	            ret_mode ="顺序";
	            break;
	        case "2":
	            ret_mode = "随机";
	            break;
	        case "3":
	            ret_mode ="循环";
	            break;

	    }
	    return ret_mode;
	}


	function  getTypeTxt( type){
	    //1:文字广播 2:音乐广播 3:文件广播 4:喊话 5:采播
	    var ret_type = "";
	    switch (type)
	    {
	        case "1":
			case "3":
				ret_type = "文字";
				break;
	        case "2":
	            ret_type = "音乐";
	            break;
	        case "4":
	            ret_type = "喊话";
	            break;
	        case "5":
	            ret_type = "采播";
	            break;
			case "6":
				ret_type = "离线";
				break;
	    }
	    return ret_type;
	}


	function  getPlayTypeTxt( play_type){
	    var ret_play_type = "";
	    switch (play_type)
	    {
	        case "0":
	            ret_play_type = "即时广播";
	            break;
	        case "1":
	            ret_play_type = "定时广播";
	            break;
	        case "2":
	            ret_play_type = "触发广播";
	            break;

	    }
	    return ret_play_type;
	}

	function getTimeName(info){

	  var  playing_time = "每周"+" ";

	 	var  array = new Array();

	    for(var brTime in info)
	    {
	        array.push(brTime);

	        array.sort();

	    }
	    array=  arrunique(array);

	    /*
	    for (var i = array.length - 1; i >= 0; i--) //去重
	    {
	        var tempvalue = array[i];
	        array[i] = "";
	        if ($.inArray(tempvalue, array))
	        {
	            array.pop();
	        }
	        else
	        {
	            array[i] = tempvalue;
	        }

	    }
	    */


	    var  dayofweek =new Array("一","二","三","四","五","六","日") ;
	    for (var item in array)
	    {

	        playing_time = playing_time + dayofweek[Number(item)] + "、";

	    }

	    if (playing_time.lastIndexOf("、"))
	    {

	        playing_time = playing_time.substring(0,playing_time.length - 1);

	    }

		return playing_time;
	}
	function getOfflineStatusText(status) {
		if (status == '0' || status == '1' || status == '2') {
			return '下发中'
		}
		if (status == '3') {
			return '下发完成'
		}
		if (status == '5' ) {
			return '部分失败'
		}
	}

	function  getStatusTxt(status){ // 0:未开始 1:开始 2：进行中 3：已结束 4：暂停
	    var play_status = "";
	    switch (status)
	    {
	        case "0":
	            play_status = "未开始";
	            break;
	        case "1":
	            play_status = "开始";
	            break;
	        case "2":
	            play_status = "进行中";
	            break;
	        case "3":
	            play_status = "已结束";
	            break;
	        case "4":
	            play_status = "暂停";
	            break;
	    }
	    return play_status;
	}

	function getPriorityTxt(priority){
	    var ret_priority = "";
	    switch (priority)
	    {
	        case "1":
	            ret_priority ="超级紧急";
	            break;
	        case "2":
	            ret_priority = "高";
	            break;
	        case "3":
	        case "4":
	            ret_priority ="中";
	            break;
	        case "5":
	            ret_priority ="低";
	            break;
	    }
	    return ret_priority;
	}
	function getB_enableTxt(b_enable){
	    return b_enable === '1' ? '已启用':'未启用';
	}

	function arrunique(arr){
	    var hash=[];
	    for (var i = 0; i < arr.length; i++) {
	    	if(hash.indexOf(arr[i])==-1){
	    	    hash.push(arr[i]);
	    	}
	    }
	     return hash;
	}

	/* 播放广播 */
	function  broadcast_start(){
	    var row = $("#broadtable").bootstrapTable("getSelections");
		if(row.length > 1 || row.length <= 0){
			$.alert('请选择一条广播任务')
			return;
		}
		let bName = row[0].name;
		//console.log("选中广播：>>"+JSON.stringify(row))
		if(row[0].b_enable === '未启用'){
			//提示广播未启用	
			$.confirm({
				title:'启用提示',
				content:'『' + bName + '』'+'广播未启用，是否现在启用并播放?',
				buttons:{
					确认:function(){
					  var f = setBroad({id:row[0].id, b_enable:'1'})
					  if(f){
						  var id = row[0].id
						  var msgtxt="'id':'"+id+"'";
						  method = "broadcast_start";
						  send(msgtxt);	

					  }else{
						//  console.log("setBroad fail")
					  }
					},
					取消: function(){
	
					}
				}
			})
		}else{
			var id = row[0].id
			var msgtxt="'id':'"+id+"'";
			method = "broadcast_start";
			send(msgtxt);
		}

	}
	/*设置任务状态*/
	function setBroad({id, b_enable}){
		var flag = false
		$.ajax({
		    url:httpProto+"://"+host+"/control/20210618/infs/setBroad.json",
			//url: 'http://127.0.0.1:8080/control/20210618/infs/setBroad.json',
		    type: "post",
		    data:JSON.stringify({"id":id,"b_enable":b_enable}),
		    dataType:"json",
			async:false,
		    contentType:"application/json",
		    success:function(response){
				 //启用
				if (response.statuscode === '000000') {
					flag = true
				}else{
					flag = false;
		        }
		    }

		})
		return flag
	}
	/* 停止广播 */
	function broadcast_stop(){
		var row = $("#broadtable").bootstrapTable('getSelections')
		if(row.length > 1 || row.length <= 0){
			$.alert('请选择一条广播任务')
			return;
		}
		var id = row[0].id
		var msgtxt = "'id':'"+id+"'"
		method = 'broadcast_stop'
		send(msgtxt)
	}
	//播放通知
	function playNotice() {
		let row = $("#noticeTable").bootstrapTable("getSelections");
		if(row.length > 1 || row.length <= 0){
			$.alert('请选择一条通知任务')
			return;
		}
		let bName = row[0].name;
		//console.log("选中广播：>>"+JSON.stringify(row))
		if(row[0].b_en === '未启用'){
			//提示通知未启用
			$.confirm({
				title:'启用提示',
				content:'『' + bName + '』'+'通知未启用，是否现在启用并播放?',
				buttons:{
					确认:function(){
						setNotice({id: row[0].id, status: '1', volume: row[0].volume,b_enable: '1'});
					},
					取消: function(){

					}
				}
			})
		}else{
			setNotice({id: row[0].id, status: '1', volume: row[0].volume});
		}
	}
	function pauseNotice() {
		let row = $("#noticeTable").bootstrapTable('getSelections')
		if(row.length > 1 || row.length <= 0){
			$.alert('请选择一条通知任务')
			return;
		}
		setNotice({id: row[0].id, status: '4', volume: row[0].volume,b_enable: '1'});
	}
	//停止通知
	function endNotice() {
		//封装日志参数
		// let broadLog = {
		// 	menu_id: '0',
		// 	sysuser_id: this.$store.state.user.sys_user_id,
		// 	// journal_title: '调度通知=>结束'
		// 	journal_title: '${i18n.dispatch_notice}=>${i18n.end}'
		// }
		let row = $("#noticeTable").bootstrapTable("getSelections");
		if(row.length > 1 || row.length <= 0){
			$.alert('请选择一条通知任务')
			return;
		}
		setNotice({id: row[0].id, status: '3', volume: row[0].volume});
	}
	function setNotice(param) {
		$.ajax({
			url:httpProto+"://"+host+"/control/20180628/infs/setCallOutTask.json",
			type: "post",
			data:JSON.stringify(param),
			dataType:"json",
			async:false,
			contentType:"application/json",
			success:function(response){
				if (response.statuscode === '000000') {
					//3秒后刷新
					setTimeout(() => {
						//生成表格
						generNoticeTable()
					}, 3 * 1000);
				}
			}

		})
	}
	//获取通知详情
	function getNoticeDetail(request) {
		$("#noticeDetail").modal("show");
		$.ajax({
			url:httpProto+"://"+host+"/control/api_v2.2.5/notice/query/queryDetailList.json",
			type: "post",
			data:JSON.stringify(request.data),
			dataType:"json",
			async:false,
			contentType:"application/json",
			headers:{
				'Authorization':authForAll,
			},
			success:function(response){
				if (response.code === 200) {
					let newData = response.data;
					let data = newData.list;
					if(data && data.length > 0){
						for (let i = 0; i < data.length; i++) {
							data[i].rownum = data[i].rowNum+'';//转换成字符串
							let time = data[i].startTime
							if (time) {
								data[i].show_result = data[i].callResult+'' === '1' ? "成功" : "失败";
								data[i].show_status = callDetailStatus(data[i].callStatus+'');
							} else {
								data[i].show_result = ''
								data[i].show_status = ''
							}
							data[i].send_result = data[i].sendResult + ''
							if (data[i].send_result === '-1') {
								data[i].show_send = "未发送"
							}else if(data[i].send_result === '1'){
								data[i].show_send = "成功"
							}else if (data[i].send_result === '0') {
								data[i].show_send = "失败"
							}else {
								data[i].show_send = "未知"
							}
						}
					}
					request.success({
						total: newData.totalCount,
						rows: data
					})
				}
			}

		})
	}
	function callDetailStatus(type) {
		if (!type) return
		if (type === '1'){
			return '已呼出'
		}else if (type === '2') {
			return '客户应答'
		}else if (type === '8') {
			return '客户挂断'
		}else {
			return '未知'
		}
	}
	function initNoticeDetail(data) {
		let row = $("#noticeTable").bootstrapTable("getSelections");
		if(row.length > 1 || row.length <= 0){
			$.alert('请选择一条通知任务')
			return;
		}
		$('#noticeDetailTable').bootstrapTable('destroy');
		$('#noticeDetailTable').bootstrapTable({
			data:data,
			clickToSelect:true,
			uniqueId:'id',
			toolbarAlign:'right',
			silent:true,
			striped:true,
			cache:false,
			showColumns:false,
			scrollbar:true,
			autoHeight: true,
			pagination: true,
			search: false,
			ajax:getNoticeDetail,
			queryParams : function (params) {
				//这里的是搜索条件
				let temp = {
					taskId:row[0].id+"",//id
					telNumber:$("#telNumber").val(),
					callResult:$("#callResultList  option:selected").val(),
					sendResult:$("#sendResultList  option:selected").val(),
					callStatus:$("#statusList  option:selected").val(),
					startTimeBegin:"",//开始时间段开始
					startTimeEnd:"",//开始时间段结束
					currPage:(params.offset / params.limit) + 1,
					pageLimit:params.limit,
				};
				return temp;
			},
			pageNumber: 1,                      //初始化加载第一页，默认第一页,并记录
			pageSize: 5,
			pageList: [10, 25, 50, 100],
			columns:[{
					field:'telNumber',
					title:'号码',
					align:'center',
					valign: 'middle',
				},{
					field:'startTime',
					title:'开始时间',
					align:'center',
					valign: 'middle',
				},{
					field:'show_result',
					title:'呼叫结果',
					align:'center',
					valign: 'middle',
				},{
					field:'show_send',
					title:'发送结果',
					align:'center',
					valign: 'middle',
				},{
					field:'show_status',
					title:'呼叫状态',
					align:'center',
					valign: 'middle',
				},{
					field:'callCount',
					title:'呼叫次数',
					align:'center',
					valign: 'middle',
				},{
					field:'notEnterNumber',
					title:'未按键通知次数',
					align:'center',
					valign: 'middle',
				},{
					field:'callLastingTime',
					title:'通话时长',
					align:'center',
					valign: 'middle',
				},]

		})
		$('#detailTableDiv').css({'height':400})
	}
	//批量删除通知任务
	function noticeBatchDelete (){
		let row = $("#noticeTable").bootstrapTable('getSelections')
		if(row.length <= 0){
			$.alert('请选择通知任务')
			return;
		}
		$.confirm({
			title:'确认删除',
			content:'确认删除'+row.length+'条通知任务?',
			buttons:{
				确认:function(){
					var fail = []
					for(var i = 0; i < row.length; i++){
						var f = doDeleteNotice(row[i].id)
						if(!f){
							fail.push(row[i].id)
						}
					}
					if(fail.length<=0){
						$.alert("删除成功!");
					}else{
						$.alert(fail+"删除失败!");
					}
					//生成表格
					generNoticeTable()
				},
				取消:function(){}
			}
		})
	}
	function noticeDelete() {
		let row = $("#noticeTable").bootstrapTable('getSelections')
		if(row.length > 1 || row.length <= 0){
			$.alert('请选择一条通知任务')
			return;
		}
		var id = row[0].id
		$.confirm({
			title:'确认删除',
			content:'确认删除此通知任务?',
			buttons:{
				确认:function(){
					var f = doDeleteNotice(id)
					if(f){
						$.alert("删除成功!");
						//生成表格
						generNoticeTable()
					}else{
						$.alert("删除失败!");
					}
				},
				取消: function(){}
			}
		})
	}
	/* 删除广播 */
	function broadcast_delete(){
		var row = $("#broadtable").bootstrapTable('getSelections')
		if(row.length > 1 || row.length <= 0){
			$.alert('请选择一条广播任务')
			return;
		}
		var id = row[0].id
		var name = row[0].name

		$.confirm({
		    title:'确认删除',
		    content:'确认删除此广播任务?',
		    buttons:{
		        确认:function(){
		        	if("6" == stype){
						broDeleteOffline(id,name)
						return;
					}
		          var f = bro_delete(id)
				  if(f){
					  $.alert("删除成功!");
					  //生成表格
					  generTaskTable()
				  }else{
					  $.alert("删除失败!");
				  }
		        },
		        取消: function(){

		        }
		    }
		})
	}

	function broadcast_batch_delete(){
		var row = $("#broadtable").bootstrapTable('getSelections')
		if(row.length <= 0){
			$.alert('请选择广播任务')
			return;
		}
		$.confirm({
			title:'确认删除',
			content:'确认删除'+row.length+'条广播任务?',
			buttons:{
				确认:function(){
					var fail = []
					for(var i = 0; i < row.length; i++){
						if("6" == stype){
							var f = broDeleteOffline(row[i].id,row[i].name,"1")
						}else{
							var f = bro_delete(row[i].id)
						}
						if(!f){
							fail.push(row[i].id)
						}
					}
					let param = "6" == stype ? "6" : "";
					if(fail.length<=0){
						$.alert("删除成功!");
						//生成表格
						generTaskTable()
					}else{
						$.alert(fail+"删除失败!");
						//生成表格
						generTaskTable()
					}
				},
				取消:function(){}
			}
		})
	}
	function broDeleteOffline(id,name,flag) {
		let isSuccess = false;
		$.ajax({
			url:httpProto+"://"+host+"/control/offlineTask/deleteTask.json",
			type: "post",
			data:JSON.stringify({"bId":id,"bName":name}),
			dataType:"json",
			async:false,
			contentType:"application/json",
			success:function(response){
				if (response.data.statuscode === '000000') {
					isSuccess = true;
					if(!flag) {
						$.alert("操作成功!");
						//3秒后刷新
						setTimeout(() => {
							//生成表格
							generTaskTable()
						}, 3 * 1000);
					}

				} else {
					if(!flag) {
						$.alert("删除失败!");
					}
				}
			}

		})
		return isSuccess
	}
	function doDeleteNotice(id) {
		let flag = false
		$.ajax({
			url:httpProto+"://"+host+"/control/20180628/infs/delCallOutTask.json",
			type: "post",
			data:JSON.stringify({"id":id}),
			dataType:"json",
			async:false,
			contentType:"application/json",
			success:function(data){
				if (data.statuscode = "000000") {
					flag = true
				}else{
					flag = false;

				}
			}

		})
		return flag
	}
	function bro_delete(id){
		var flag = false
		$.ajax({
		    url:httpProto+"://"+host+"/control/20180628/infs/delBroadTask.json",
		    type: "post",
		    data:JSON.stringify({"task_id":id}),
		    dataType:"json",
			async:false,
		    contentType:"application/json",
		    success:function(data){
		        if (data.statuscode = "000000") {
		            flag = true
		        }else{
					flag = false;

		        }
		    }

		})
		return flag
	}

	/* 添加音量 */
	function broadcast_addvol(){
		var row = $("#broadtable").bootstrapTable('getSelections')
		if(row.length > 1 || row.length <= 0){
			$.alert('请选择一条广播任务')
			return;
		}
		if(row[0].status !== '开始' && row[0].status !== '进行中'){
			$.alert(row[0].name+'：广播未开始')
			return;
		}
		let selectVol = $("#broadtable tr.selected td").eq(-2).text();
		var vol =Number(selectVol);
		/*if(vol >= 4 ){
			$.alert('音量已达最大')
			return;
		} */
		vol = vol + 1;
		if(vol > 4){vol = 4};
		$("#broadtable tr.selected td").eq(-2).text(vol);
		var id = row[0].id
		broadcast_setvol(id,vol)
	}
	/* 减小音量 */
	function broadcast_downvol(){
		var row = $("#broadtable").bootstrapTable('getSelections')
		if(row.length > 1 || row.length <= 0){
			$.alert('请选择一条广播任务')
			return;
		}
		if(row[0].status !== '开始' && row[0].status !== '进行中'){
			$.alert(row[0].name+'：广播未开始')
			return;
		}
		let selectVol = $("#broadtable tr.selected td").eq(-2).text();
		var vol =Number(selectVol);
		/*if(vol <= -4 ){
			$.alert('音量已达最小')
			return;
		} */
		vol = vol - 1;
		if(vol < -4){vol = -4};
		$("#broadtable tr.selected td").eq(-2).text(vol);
		var id = row[0].id
		broadcast_setvol(id,vol)
	}
	//设置音量
	function  broadcast_setvol(id,vol){

	 var msgtxt="'id':'"+id+"','vol':'"+vol+"'";
	 method = "broadcast_setvol";
	 send(msgtxt);

	}

	function openTaskDetail(request) {
		$("#offlineDetail").modal("show");
		$.ajax({
			url: httpProto+'://'+host+'/control/api_v2.2.5/broad/offlineTask/getOfflineDetails.json',
			type: 'get',
			data: request.data,
			dataType: 'json',
			headers:{
				'Authorization':authForAll
			},
			success:function(data){
				if (data.code === 200) {
					let newData = data.data;
					if(newData.list && newData.list.length > 0){
						for (let i = 0; i < newData.list.length; i++) {
							newData.list[i].newStatus = transformIssuedStatus(newData.list[i].status);
							newData.list[i].failReason = transformFailReason(newData.list[i].failCause);
						}
					}
					request.success({
						total: newData.totalCount,
						rows: newData.list
					})
				}else{
					alert('加载数据出错')
				}
			}
		})
	}
	function initTaskDetail() {
		let row = $("#broadtable").bootstrapTable('getSelections')
		if(row.length > 1 || row.length <= 0){
			$.alert('请选择一条广播任务')
			return;
		}
		$('#detailTable').bootstrapTable('destroy');
		$('#detailTable').bootstrapTable({
			cache:false,
			data:'',
			clickToSelect:true,
			uniqueId:'id',
			showColumns:false,
			scrollbar:true,
			autoHeight: true,
			ajax:openTaskDetail,
			queryParams : function (params) {
				//这里的是搜索条件
				let temp = {
					id:row[0].id+"",//id
					currPage:(params.offset / params.limit) + 1,
					pageLimit:params.limit,
				};
				return temp;
			},
			search:false,
			height:'500px',
			pagination: true,
			pageNumber:1,
			sidePagination:'server',
			pageSize:10,
			pageList:[10, 20, 50, 100],
			columns:[
				{
					field:'exten',
					title:'终端',
					align:'center',
					valign: 'middle',
				},{
					field:'newStatus',
					title:'下发状态',
					align:'center',
					valign: 'middle',
				},{
					field:'failReason',
					title:'失败原因',
					align:'center',
					valign: 'middle',
				},{
					field:'remarks',
					title:'操作',
					align:'center',
					width:120,
					valign: 'middle',
					formatter: function(value,row,index){
						let param = row.status =='2' ? '重新下发' : '重试';
						let e = "";
						if(row.status =='6' || row.status =='3' || row.status =='2'){
							e += "<a href='javascript:;' onclick='retry("+row.status+","+row.id+","+row.exten+")'>"+param+"</a> ";
						}
						if(row.status =='6'){
							param =  '强制删除';
							e += "<a href='javascript:;' onclick='forceDelete("+row.id+","+row.exten+")'>"+param+"</a> ";
						}
						return e;
					}
				}]

		})
		$('#broadDetailTable').css({'height':400})
	}
	function retry(isUsedStatusDict,bId,exten) {
		let operation = ''
		if (isUsedStatusDict === '3' || isUsedStatusDict === '2') {//同步失败(或者已同步) ==》 重新同步
			operation = 'sync'
		}
		if (isUsedStatusDict === '6') {//删除失败 ==》重新删除
			operation = 'delete'
		}
		$.ajax({
			url: httpProto+'://'+host+'/control/offlineTask/retry.json',
			type: 'get',
			data: {
				operation:operation,
				bId:bId,
				exten:exten
			},
			dataType: 'json',
			success:function(data){
				if (data.code === 200) {
					setTimeout(function () {
						initTaskDetail();
					},2000);
				}else{
					alert('加载数据出错')
				}
			}
		})
	}
	function forceDelete(bId,exten) {
		$.ajax({
			url: httpProto+'://'+host+'/control/offlineTask/forceDelete.json',
			type: 'get',
			data: {
				bId:bId,
				exten:exten
			},
			dataType: 'json',
			success:function(data){
				if (data.code === 200) {
					setTimeout(function () {
						initTaskDetail();
					},1000);
				}else{
					alert('加载数据出错')
				}
			}
		})
	}
	function transformFailReason(failReason) {
		let retValue = ''
		switch (failReason) {

			case "1"://发送失败
				retValue = '发送失败'
				break;
			case "2"://响应超时
				retValue = '响应超时'
				break;
			default:
				break;
		}
		return retValue
	}
	function transformIssuedStatus(issuedStatus) {
		let retValue = ''
		switch (issuedStatus) {
			case "0"://开始同步
				retValue = '开始同步'
				break;

			case "1"://同步中
				retValue = '同步中'
				break;

			case "2"://已同步
				retValue = '已同步'
				break;

			case "3"://同步失败
				retValue = '同步失败'
				break;

			case "4"://开始删除
				retValue = '开始删除'
				break;

			case "5"://删除中
				retValue = '删除中'
				break;

			case "6"://删除失败
				retValue = '删除失败'
				break;

			default:
				break;
		}

		return retValue

	}
	function changePlayingMode() {
		let v = $("#playingMode option:selected").val()+"";
		if(v == "1"){
			$("#brotime").attr("hidden","hidden");
			return;
		}
		$("#brotime").removeAttr("hidden");
	}
	function broadcast_edit(){
		getAudioList();
		var row = $("#broadtable").bootstrapTable('getSelections')
		if(row.length > 1 || row.length <= 0){
			$.alert('请选择一条广播任务')
			return;
		}
		var id = row[0].id
		//标识是添加操作
		isEdit = true;
		showPlayType(false)
		refreshTree();
		$("#typeDiv").removeAttr("hidden");
		$("#threeLine").removeAttr("hidden");
		$("#fourLine").removeAttr("hidden");
		$("#pstnDiv").removeAttr("hidden");
		$("#playFileTypeDiv").attr("hidden","hidden");
		$("#textContentDiv").attr("hidden","hidden");
		$("#modeDiv").attr("hidden","hidden");
		$("#textContentDiv").attr("hidden","hidden");
		$("#audioIdDiv").attr("hidden","hidden");
		$("#musicListDiv").attr("hidden","hidden");
		$("#timeOfflineDiv").attr("hidden","hidden");
		$("#enableDiv").removeAttr("hidden");
		$("#timeDiv").removeAttr("hidden");
		$("#playTimeTypeDiv").removeAttr("hidden");
		if("6" == stype){
			$("#playTimeTypeDiv").attr("hidden","hidden");
			$("#timeDiv").attr("hidden","hidden");
			$(".btype").attr("hidden","hidden");
			$("#brotimes").attr("hidden","hidden");
			$("#brosip").attr("hidden","hidden");
			$("#bromusic").attr("hidden", "hidden");
			$("#brotextarea").attr("hidden","hidden");
			$("#brofile").attr("hidden", "hidden");
			$("#voicenum").attr("hidden","hidden");
			$("#pstnDiv").attr("hidden","hidden");
			$("#threeLine").attr("hidden","hidden");
			$("#fourLine").attr("hidden","hidden");
			$("#typeDiv").attr("hidden","hidden");
			$("#enableDiv").attr("hidden","hidden");
			$("#playFileTypeDiv").removeAttr("hidden");
			$("#textContentDiv").removeAttr("hidden");
			$("#modeDiv").removeAttr("hidden");
			$("#timeOfflineDiv").removeAttr("hidden");
			get_one_broadcast(id);
			return;
		}
		//重新装填pstn
		getPstn(id,"broad");
		get_one_broadcast(id);

	}

	function submitEdit(){
		var data = {};
		if(stype == '6'){
			data = getOfflineData()
			if(data){
				updateOfflineTask(data);
			}
			return;
		}
		data = getData()
		if(!data){
			return;
		}
		$.ajax({
			url:httpProto+'://'+host+'/control/api-v2.2.3/20180628/infs/updateBroadTask.json',
			dataType:'json',
			type:'post',
			data:data,
			async:false,
			contentType:'application/json',
			success:function(result){
				if(result.statuscode == '000000'){
					$('#broadClose').click();
					$.alert('修改成功！')
					$(".tow_nav").html(svalue)
					//生成表格
					generTaskTable()
				}else{
					$.alert('修改失败')
				}
			}
		})
	}

	function noticeSubmitEdit(){
		let data = getNoticeData();
		if(!data){
			return;
		}
		$.ajax({
			url:httpProto+'://'+host+'/control/20180628/infs/updateCallOutTask.json',
			dataType:'json',
			type:'post',
			data:data,
			contentType:'application/json',
			headers:{
				"Menu_id":'10902',
				"Sysuser_id":userId,
				"Journal_title":'${i18n.dispatch_notice}=>${i18n.add}'
			},
			success:function(result){
				if(result.statuscode == '000000'){
					$.alert('编辑成功！')
					//生成表格
					generNoticeTable()
				}else{
					$.alert('编辑失败')
				}
				$('#closeNotice').click();
			}
		})
	}
	function noticeSubmitAdd(){
		let data = getNoticeData();
		if(!data){
			return;
		}
		$.ajax({
			url:httpProto+'://'+host+'/control/20180628/infs/addCallOutTask.json',
			dataType:'json',
			type:'post',
			data:data,
			contentType:'application/json',
			headers:{
				"Menu_id":'10902',
				"Sysuser_id":userId,
				"Journal_title":'${i18n.dispatch_notice}=>${i18n.add}'
			},
			success:function(result){
				if(result.statuscode == '000000'){
					$.alert('添加成功！')
					//生成表格
					generNoticeTable()
				}else{
					$.alert('添加失败')
				}
				$('#closeNotice').click();
			}
		})
	}
	function clearForm(form) {
	    // input清空
	    $(':input', form).each(function () {
	        var type = this.type;
	        var tag = this.tagName.toLowerCase(); // normalize case
	        if (type == 'text' || type == 'password' || tag == 'textarea')
	            this.value = "";
	            // 多选checkboxes清空
	            // select 下拉框清空
	        else if (tag == 'select')
	            this.selectedIndex = 0;
			else if (type == 'checkbox')
				this.checked = false;
	    });
		$("#broadcasttype").removeAttr("disabled")
		$("#voice").slider("setValue",0)//默认为0
		//$('#broadcastfile').fileinput('filedelete')
		$('.fileinput-remove-button').click()
	}



	function updateOfflineTask(s) {
		$.ajax({
			url:httpProto+'://'+host+'/control/offlineTask/updateTask.json',
			type:'post',
			data:JSON.stringify(s),
			dataType:'json',
			async:false,
			contentType:'application/json',
			success:function(result){
				if(result.code == 200){
					$('#broadClose').click();
					$.alert('编辑成功')
					$(".tow_nav").html(svalue)
					//生成表格
					generTaskTable()
				}else{
					$.alert('编辑失败')
				}
			}
		})
	}
	function addOfflineTask(s) {
		$.ajax({
			url:httpProto+'://'+host+'/control/api-v2.2.9/offlineTask/addTask.json',
			type:'post',
			data:JSON.stringify(s),
			dataType:'json',
			async:false,
			contentType:'application/json',
			success:function(result){
				if(result.code == 200){
					$('#broadClose').click();
					$.alert('添加成功')
					$(".tow_nav").html(svalue)
					//生成表格
					generTaskTable()
				}else{
					$.alert('添加失败')
				}
			}
		})
	}
	function submitAdd(){
		var data = {};
		if(stype == '6'){
			data = getOfflineData()
			if(data){
				addOfflineTask(data);
			}
			return;
		}
		data = getData()
		if(!data){
			return;
		}
		/* delete data['id']
		delete data['task_id'] */
		var s = JSON.parse(data)
		delete s['id']
		delete s['task_id']
		$.ajax({
			url:httpProto+'://'+host+'/control/api-v2.2.3/20180628/infs/addBroadTask.json',
			type:'post',
			data:JSON.stringify(s),
			dataType:'json',
			async:false,
			contentType:'application/json',
			success:function(result){
				if(result.statuscode == '000000'){
					$('#broadClose').click();
					$.alert('添加成功')
					$(".tow_nav").html(svalue)
					//生成表格
					generTaskTable()
				}else{
					$.alert('添加失败')
				}
			}
		})
	}
	function changePlayType(val){
		if (val == null || val == undefined || val == "") {
			val = $("#playFileType option:selected").val();
		}
		$("#textContentDiv").attr("hidden","hidden");
		$("#audioIdDiv").attr("hidden","hidden");
		$("#musicListDiv").attr("hidden","hidden");
		if("3" == val){
			$("#textContentDiv").removeAttr("hidden");
		}else if("2" == val){
			$("#musicListDiv").removeAttr("hidden");
		}else{
			$("#audioIdDiv").removeAttr("hidden");
		}
	}
	function getFjList(loginName,passWord){
	   var base = new Base64();
	   var str = loginName+":"+passWord
	   var Authorization = base.encode(str)
	   $.ajax({
	       url:httpProto+"://"+host+"/control/20140901/infs/login.json",
	       type:"get",
	       async:false,
	       beforeSend:function(request){
	         request.setRequestHeader("Authorization",Authorization)
	       },
	       dataType:"json",
	       contentType:"application/json",
	       success:function(data){
			   

	       }
	   })
	}
	function getSmsList() {
		var base = new Base64();
		var Authorization = base.encode(username+":"+password)
		$.ajax({
			url:httpProto+"://"+host+"/control/20200718/infs/getSmsTemplate.json",
			type:"get",
			data:{language:"zh-CN"},
			contentType:"application/json",
			dataType:"json",
			beforeSend:function(request){
				request.setRequestHeader("Authorization",Authorization)
			},
			async:true,
			success:function(data){
				if (data.statuscode == "000000") {
					let smsList = data.data
					let str = " <option onclick='setSmsContent('')' value=\"\">请选择</option>"
					let id = ""
					let value = ""
					let smsContent="";
					let strOne = "";
					for (let i = 0; i < smsList.length; i++) {
						for (let key in smsList[i]){
							if (key == "id") {
								id = smsList[i][key]
							}
							if (key=="template_no") {
								value = smsList[i][key]
							}
							if (key=="template_content") {
								smsContent = smsList[i][key]
							}
						}
						str += "<option value='"+id+"'>"+value+"</option>"
						strOne += "<input style='display: none' id='smsIdInput"+id+"' value='"+smsContent+"'/>"
					}
					$("#smsModal").html(str);
					$("#smsHiddenDiv").html(strOne);
				}
			}
		})
	}
	function getPstn(taskId,type){
	    if (taskId == undefined || taskId == null) {
	        taskId=""
	    }
	    let taskType = '1';
	    if(taskId && 'notice' == type){
			taskType = "3";
		}
	   $.ajax({
	       url:httpProto+"://"+host+"/control/20180628/infs/getAccessnumList.json",
	       type:"post",
	       data:JSON.stringify({"task_id":taskId,"task_type":taskType}),
	       contentType:"application/json",
	       dataType:"json",
		   async:false,
	       success:function(data){
	           if(data.statuscode=="000000"){
	               var pstns = data.access_num.split(",");
	               var str = "<option value=\"\">请选择接入号(选填)</option>";
	               for(var i=0;i<pstns.length;i++){
	                   str += "<option value='"+pstns[i]+"'>"+pstns[i]+"</option>";
	               }
	               $("#broadcastpstn").html(str);
	               $("#pstnNum").html(str);
	           }
	       }
	   });
	}

	function getAudioList() {
	    $.ajax({
	        url:httpProto+"://"+host+"/control/20210928/infs/getMusicStoreList.json",
	        type:"post",
			data:JSON.stringify({deptId:deptId,isAdmin:isAdmin}),
	        contentType:"application/json",
	        dataType:"json",
			async:false,
	        success:function(data){
	            if (data.statuscode == "000000") {
	                var audioList = data.data
					allAudioList = data.data
	                var str = "<option value=\"\">请选择提示音(选填)</option>"
					var strOne = "<option value=\"\">请选择音乐文件</option>";
					var strFive = "<option value=\"\">请选择录音文件</option>";
	                var strThree = "";
	                var strFour = "";
	                for (var i = 0; i < audioList.length; i++) {
	                    var audio = audioList[i];
	                    var value = "";
	                    var id = "";
	                    var audioPath = "";
	                    for (var key in audio) {
	                        if (key=="id"){
	                            id = audio[key];
	                        }
	                        if (key == "audio_name") {
	                            value=audio[key];
	                        }
							if (key=="path") {
								audioPath = audio[key]
							}
	                    }
	                    str +="<option value='"+id+"'>"+value+"</option>"
						strOne +="<option value='"+id+"'>"+value+"</option>"
						strFive +="<option value='"+id+"'>"+value+"</option>"
						strThree += "<input style='display: none' id='musicInput"+id+"' value='"+audioPath+"'/>"
						strFour += "<input style='display: none' id='broadMusicInput"+id+"' value='"+audioPath+"'/>"
	                }
	                $("#tipsmusic").html(str)
					$("#broadcastVoice").html(strOne)
					$("#musicList").html(strOne)
					$("#musicHidden").html(strThree);
					$("#broadcastVoiceHidden").html(strFour);
					$("#noticeVoice").html(strFive)
	            }
	        }
	    })
	}

	function getSipCounts(){
	   $.ajax({
	       url:httpProto+"://"+host+"/control/20180628/infs/getSipaccount.json",
	       type:"get",
	       contentType:"application/json",
	       dataType:"json",
		   data:{deptId:deptId,isAdmin:isAdmin},
		   async:false,
	       success:function(data){
	           if (data.statuscode == "000000") {
	               var sipdata = data.data
	               var str = "<option value=\"\">请选择采播终端</option>";
	               for (var i = 0; i < sipdata.length; i++) {
	                   str += "<option value='"+sipdata[i].id+"'>"+sipdata[i].id+"</option>"
	               }
	               $("#broadcastsip").html(str);
	           }
	       }
	   })
	}

	function getPlayList(){
	   $.ajax({
	       url:httpProto+"://"+host+"/control/20180628/infs/getPlayList.json",
	       type:"get",
	       contentType:"application/json",
	       dataType:"json",
		   async:false,
	       success:function(data){
	           if (data.statuscode == "000000") {
	               var playList = data.data
	               var str = " <option value=\"\">请选择</option>"
	               var id = ""
	               var value = ""
	               for (var i = 0; i < playList.length; i++) {
	                   for (var key in playList[i]){
	                       if (key == "id") {
	                           id = playList[i][key]
	                       }
	                       if (key=="play_name") {
	                           value = playList[i][key]
	                       }
	                   }
	                   str += "<option value='"+id+"'>"+value+"</option>"
	               }
	               $("#audiolist").html(str);
	           }
	       }
	   })
	}

	//改变标签
	function changeHtml(times,time,sip,music,textarea,file,voice){
	    if (times){
	        $("#brotimes").removeAttr("hidden")
	    } else {
	        $("#brotimes").attr("hidden","hidden")
	    }
	    if (time){
	        $("#brotime").removeAttr("hidden")
	    } else {
	        $("#brotime").attr("hidden","hidden")
	    }
	    if(sip){
	        $("#brosip").removeAttr("hidden")
	    } else {
	        $("#brosip").attr("hidden","hidden")
	    }
	    if (music){
	        $("#bromusic").removeAttr("hidden")
	    } else{
	        $("#bromusic").attr("hidden", "hidden")
	    }
	    if (textarea){
	        $("#brotextarea").removeAttr("hidden")
	    } else{
	        $("#brotextarea").attr("hidden","hidden")
	    }
	    if (file || textarea){
	        $("#brofile").removeAttr("hidden")
	    } else {
	        $("#brofile").attr("hidden", "hidden")
	    }
	    if(voice){
	        $("#voicenum").removeAttr("hidden")
	    } else {
	        $("#voicenum").attr("hidden","hidden")
	    }

	}

	function showPlayType(flag){
	    if(flag){
	        $(".btype").removeAttr("hidden");
			$('.high').hide()
			$(".submit-add").show();
			$('.submit-edit').hide();
	    }else {
	        $(".btype").attr("hidden", "hidden");
			$('.high').show()
			$(".submit-add").hide();
			$('.submit-edit').show();
	    }
	}
	function changeFileType(val){
		if (val == null || val == undefined || val == "") {
			val = $("#play_file_type option:selected").val();
		}
		$("#brotextarea").attr("hidden","hidden")
		$("#broadFile").attr("hidden","hidden")
		$("#broadVoiceList").attr("hidden","hidden")
		switch (val) {
			case "1":
				$("#broadFile").removeAttr("hidden")
				break;
			case "2":
				$("#broadVoiceList").removeAttr("hidden")
				break;
			case "3":
				$("#brotextarea").removeAttr("hidden")
				break;
		}
	}
	function changeOption(val){
	    if (val == null || val == undefined || val == "") {
	        val = $("#broadcasttype option:selected").val();
	    }
		$("#playTimeTypeDiv").removeAttr("hidden")
	    switch (val) {
	        case "1":
			case "3":
				let play_file_type = $("#play_file_type option:selected").val();
				if(play_file_type == '3'){
					changeHtml(true,true,false,false,true,true,true)
				}else{
					changeHtml(true,true,false,false,false,true,true)
				}
				break;
	        case "2":
				$("#playTimeTypeDiv").attr("hidden","hidden");
				changeHtml(true,true,false,true,false,false,true)
	            break;
	        case "4":
				$("#playTimeTypeDiv").attr("hidden","hidden");
	            changeHtml(false,false,false,false,false,false,false)
	            break;
	        case "5":
				$("#playTimeTypeDiv").attr("hidden","hidden");
	            changeHtml(false,true,true,false,false,false,false)
	            break;
	        default:
	            changeHtml(true,false,false,false,true,false,true)
	            break;
	    }
		if(!isEdit && '5' != val && '4' != val){
			switch (val) {
				case '1':
					set_select_checked("playTimeType",'1')
					break
				case '2':
					set_select_checked("playTimeType",'0')
					break
				case '3':
					set_select_checked("playTimeType",'1')
					break
			}
			changPlayTimeType();
			return;
		}
		let play_time_type = $('#playTimeType option:selected').val();
		if(isEdit && !play_time_type){
			switch (val) {
				case '1':
					set_select_checked("playTimeType",'1')
					break
				case '2':
					set_select_checked("playTimeType",'0')
					break
				case '3':
					set_select_checked("playTimeType",'1')
					break
			}
		}
		if('5' != val && '4' != val){
			changPlayTimeType();
		}
		//触发高级记忆功能
		memberLastRecord();
	}

	function changeTimeArea(){
		var radioValue = $('input[name="timetype"]:checked').val();
		if(radioValue==1){
			$("#timetypeOne").removeAttr("hidden")
			$("#timetableOffline").attr("hidden","hidden")

			$("#timeinput").removeAttr("hidden")
			$("#timetable").attr("hidden","hidden")
		}else{
			$("#timetypeOne").attr("hidden","hidden")
			$("#timetableOffline").removeAttr("hidden")

			$("#timetable").removeAttr("hidden")
			$("#timeinput").attr("hidden","hidden")
		}
	}
	function generTable(times,type){//type: 0-时间表格 1-节假日表格

		if(times == null || times == "" || times == undefined){
			times = []
		}

		if (type == 0) {
			console.log("generTable() ==>>>> type:"+type)
			var data=[].concat(times)
			$("#bootstrap-table").bootstrapTable("destroy");
			$("#bootstrap-table").bootstrapTable({
				//showFullscreen:true,
				toolbarAlign:'right',
				toolbar:'#toolbar',
				silent:true,
				data:data,
				striped:true,
				cache:false,
				selectItemName:'btTimeItem',
				//showColumns:true,
				clickToSelect:true,
				uniqueId:'index',
				columns:[{
					checkbox:true,
				},{
					field:'index',
					title:'序号'
				},{
					field:'Mon',
					title:'周一'
				},{
					field:'Tue',
					title:'周二'
				},{
					field:'Wed',
					title:'周三'
				},{
					field:'Thu',
					title:'周四'
				},{
					field:'Fri',
					title:'周五'
				},{
					field:'Sat',
					title:'周六'
				},{
					field:'Sun',
					title:'周日'
				}],
				onDblClickCell: function(field,value,row,$element){
	
					var upIndex = $element[0].parentElement.rowIndex - 1;
					if(field == 'Mon' || field == 'Tue' || field == 'Wed' || field == 'Thu' || field == 'Fri' || field == 'Sat' || field == 'Sun'){
						$element[0].innerHTML="<input id='inputCell' type='text' name='inputCell' style='width:auto;' value='"+value+"'>";
						$("#inputCell").focus();
						$("#inputCell").blur(function(){
							var newValue = $("#inputCell").val();
							row[field] = newValue;
							$(this).remove()
							$("#bootstrap-table").bootstrapTable('updateCell',{
								index:upIndex,
								field:field,
								value:newValue
							});
						})
					}
				}
			})
			$("#bootstrap-table").bootstrapTable('hideColumn', 'index');
			this.checkBox($("#bootstrap-table"))
		}

		if (type == 1) {
			console.log("generTable() ==>>>> type:"+type)
				    var data=[].concat(times)
	    $("#bootstrap-table-holiday").bootstrapTable("destroy");
	    $("#bootstrap-table-holiday").bootstrapTable({
	        //showFullscreen:true,
	        toolbarAlign:'right',
	        toolbar:'#toolbar-holiday',
	        silent:true,
	        data:data,
	        striped:true,
	        cache:false,
			selectItemName:'btTimeItem',
	        //showColumns:true,
	        clickToSelect:true,
	        uniqueId:'index',
	        columns:[{
	            checkbox:true,
	        },{
	            field:'index',
	            title:'序号'
	        },{
				field:'id',
				title:'ID',
				visible:false

			},{
	            field:'month',
	            title:'月份'
	        },{
	            field:'date',
	            title:'日期'
	        },{
	            field:'startTime',
	            title:'开始时间'
	        },{
	            field:'endTime',
	            title:'截至时间'
	        },{
	            field:'remark',
	            title:'备注'
	        }
				],
			onDblClickCell: function(field,value,row,$element){

				var upIndex = $element[0].parentElement.rowIndex - 1;
				if(field == 'id'||field == 'month' || field == 'date' || field == 'startTime' || field == 'endTime' || field == 'remark'){
					$element[0].innerHTML="<input id='inputCell2' type='text' name='inputCell2' style='width:auto;' value='"+value+"'>";
					$("#inputCell2").focus();
					$("#inputCell2").blur(function(){
						var newValue = $("#inputCell2").val();
						row[field] = newValue;
						$(this).remove()
						$("#bootstrap-table-holiday").bootstrapTable('updateCell',{
							index:upIndex,
							field:field,
							value:newValue
						});
					})
				}
			}
	    })
	    $("#bootstrap-table-holiday").bootstrapTable('hideColumn', 'index');
	    this.checkBox($("#bootstrap-table-holiday"))
		}

	}
	var x,y;
	$(document).mousemove(function(e){
		x = e.pageX;
		y = e.pageY;
	});
	function showDept(param) {
		if("1" == param){
			$('#deptTreeForBroad').css('display','block')
			$('#deptTreeForBroad').treeview('search', [ $('#deptInputForBroad').val(), { ignoreCase: false, exactMatch: false } ]);
		}else{
			var div = $("#deptTreeForBroad");//获取你想要的DIV
			var y1 = div.offset().top;  //div上面两个的点的y值
			var y2 = y1 + div.height();//div下面两个点的y值
			var x1 = div.offset().left;  //div左边两个的点的x值
			var x2 = x1 + div.width();  //div右边两个点的x的值
			if( x < x1 || x > x2 || y < y1 || y > y2){
				$('#deptTreeForBroad').css('display','none')
			}

		}
	}
	function showNoticeDept(param) {
		if("1" == param){
			$('#deptTreeForNotice').css('display','block')
			$('#deptTreeForNotice').treeview('search', [ $('#deptInputForNotice').val(), { ignoreCase: false, exactMatch: false } ]);
		}else{
			var div = $("#deptTreeForNotice");//获取你想要的DIV
			var y1 = div.offset().top;  //div上面两个的点的y值
			var y2 = y1 + div.height();//div下面两个点的y值
			var x1 = div.offset().left;  //div左边两个的点的x值
			var x2 = x1 + div.width();  //div右边两个点的x的值
			if( x < x1 || x > x2 || y < y1 || y > y2){
				$('#deptTreeForNotice').css('display','none')
			}

		}
	}
	function showCheckDept(param) {
		if("1" == param){
			$('#deptTreeForCheck').css('display','block')
			$('#deptTreeForCheck').treeview('search', [ $('#deptInputForCheck').val(), { ignoreCase: false, exactMatch: false } ]);
		}else{
			var div = $("#deptTreeForCheck");//获取你想要的DIV
			var y1 = div.offset().top;  //div上面两个的点的y值
			var y2 = y1 + div.height();//div下面两个点的y值
			var x1 = div.offset().left;  //div左边两个的点的x值
			var x2 = x1 + div.width();  //div右边两个点的x的值
			if( x < x1 || x > x2 || y < y1 || y > y2){
				$('#deptTreeForCheck').css('display','none')
			}
		}
	}
	//新填一行
	function addRow(type){
		//type : 0-时间表格 1-节假日表格 2-调度通知循环表格
		if (type == 0) {//0-时间表格
	
		var length = $("#bootstrap-table").bootstrapTable('getData').length;
	    $("#bootstrap-table").bootstrapTable('insertRow',{
	        index:length,
	        row:{
	            index:length,
	            Mon:'10:00:00',
	            Tue:'10:00:00',
	            Wed:'10:00:00',
	            Thu:'10:00:00',
	            Fri:'10:00:00',
	            Sat:'',
	            Sun:''
	        }
	    })
	    this.checkBox($("#bootstrap-table"))
	}	

		if (type == 1) {//1-节假日表格
		var length = $("#bootstrap-table-holiday").bootstrapTable('getData').length;

		var startTime = $("#starttime-holiday").val();
		var endTime = $("#endtime-holiday").val();
		var remark = $("#remark-holiday").val();

		if ( startTime !="" && endTime !="") {

			let arr = getDayAll(startTime,endTime)
        for (let i = 0; i < arr.length; i++) {  
			$("#bootstrap-table-holiday").bootstrapTable('insertRow',{
				index:length,
				row:{
					index:length,
					id:Date.now() + Math.random().toString(16),
					date:arr[i].split('-')[1],
					month:arr[i].split('-')[0],
					startTime:'00:00:00',
					endTime:'23:59:59',
					remark:remark
				}
			})
			this.checkBox($("#bootstrap-table-holiday"))

			length = length +1;  

		}
		
		

	}	

	}

		if(type == 2){
			var length = $("#noticeBootstrap-table").bootstrapTable('getData').length;
			$("#noticeBootstrap-table").bootstrapTable('insertRow',{
				index:length,
				row:{
					index:length,
					Mon:'10:00:00',
					Tue:'10:00:00',
					Wed:'10:00:00',
					Thu:'10:00:00',
					Fri:'10:00:00',
					Sat:'',
					Sun:''
				}
			})
			this.checkBox($("#noticeBootstrap-table"))
		}
		if(type == 3){
			var length = $("#checkBootstrap-table").bootstrapTable('getData').length;
			$("#checkBootstrap-table").bootstrapTable('insertRow',{
				index:length,
				row:{
					index:length,
					Mon:'10:00:00',
					Tue:'10:00:00',
					Wed:'10:00:00',
					Thu:'10:00:00',
					Fri:'10:00:00',
					Sat:'',
					Sun:''
				}
			})
			this.checkBox($("#checkBootstrap-table"))
		}
		if(type == 4){
			var length = $("#chimeBootstrap-table").bootstrapTable('getData').length;
			$("#chimeBootstrap-table").bootstrapTable('insertRow',{
				index:length,
				row:{
					index:length,
					One:'',
					Two:'-',
					Three:'',
				}
			})
			this.checkBox($("#chimeBootstrap-table"))
		}
	}
	/**
 * 获取2个日期相隔的所有日期
 * @param starDay
 * @param endDay
 */
function getDayAll(starDay, endDay){
	let arr = []
	let dates = []
	let db = new Date(starDay)
	let de = new Date(endDay)
  
	let s = db.getTime() - 24 * 60 * 60 * 1000
	let d = de.getTime() - 24 * 60 * 60 * 1000
	for (let i = s; i <= d;) {
	  i = i + 24 * 60 * 60 * 1000
	  arr.push(parseInt(i))
	}
  
	for (let j in arr) {
	  let time = new Date(arr[j])
	  let mouth = (time.getMonth() + 1) >= 10 ? (time.getMonth() + 1) : ('0' + (time.getMonth() + 1))
	  let day = time.getDate() >= 10 ? time.getDate() : ('0' + time.getDate())
	  if (isNaN(mouth)) {
		continue
	  }
	  let MMDD = mouth + '-' + day
	  dates.push(MMDD)
	}
	return dates
  }
	function remove(type){//type: 0-时间表格 1-节假日表格

		if (type == 0) {
			var delIndex = []
		var row = $("#bootstrap-table").bootstrapTable("getSelections");
		$.each(row,function(i,e){
			delIndex.push(e.index)
		})
		removeRow(delIndex,type)
		}

		if (type == 1) {
			var delIndex = []
		var row = $("#bootstrap-table-holiday").bootstrapTable("getSelections");
		$.each(row,function(i,e){
			delIndex.push(e.index)
		})
		removeRow(delIndex,type)
		}

		if(type == 2){
			var delIndex = []
			var row = $("#noticeBootstrap-table").bootstrapTable("getSelections");
			$.each(row,function(i,e){
				delIndex.push(e.index)
			})
			removeRow(delIndex,type)
		}
		if(type == 3){
			var delIndex = []
			var row = $("#checkBootstrap-table").bootstrapTable("getSelections");
			$.each(row,function(i,e){
				delIndex.push(e.index)
			})
			removeRow(delIndex,type)
		}
		if(type == 4){
			var delIndex = []
			var row = $("#chimeBootstrap-table").bootstrapTable("getSelections");
			$.each(row,function(i,e){
				delIndex.push(e.index)
			})
			removeRow(delIndex,type)
		}
		
	}
	function removeRow(indexs,type){//type: 0-时间表格 1-节假日表格

		if (type == 0) {
			var length = $("#bootstrap-table").bootstrapTable('getData').length;
			if (length>0){
				$("#bootstrap-table").bootstrapTable("remove",{
					field:'index',
					values:indexs
				})
			}
		}

		if (type == 1) {
			var length = $("#bootstrap-table-holiday").bootstrapTable('getData').length;
			if (length>0){
				$("#bootstrap-table-holiday").bootstrapTable("remove",{
					field:'index',
					values:indexs
				})
			}
		}

		if (type == 2) {
			var length = $("#noticeBootstrap-table").bootstrapTable('getData').length;
			if (length>0){
				$("#noticeBootstrap-table").bootstrapTable("remove",{
					field:'index',
					values:indexs
				})
			}
		}
		if (type == 3) {
			var length = $("#checkBootstrap-table").bootstrapTable('getData').length;
			if (length>0){
				$("#checkBootstrap-table").bootstrapTable("remove",{
					field:'index',
					values:indexs
				})
			}
		}
		if (type == 4) {
			var length = $("#chimeBootstrap-table").bootstrapTable('getData').length;
			if (length>0){
				$("#chimeBootstrap-table").bootstrapTable("remove",{
					field:'index',
					values:indexs
				})
			}
		}

	}

	function showTimeArea(){
	     var v = $("#btype option:selected").val();
		 let b = $("#playType option:selected").val();
		 let d = $("#checkType option:selected").val();
		if(d == "1"){
			$("#checkEnableDiv").removeAttr("hidden")
			$("#checkPlayTimeDiv").removeAttr("hidden")
			$("#CheckTimeDiv").removeAttr("hidden")
		}else{
			$("#checkEnableDiv").attr("hidden", "hidden");
			$("#checkPlayTimeDiv").attr("hidden", "hidden");
			$("#CheckTimeDiv").attr("hidden", "hidden");
		}
		 if(b == "1"){
			 memberLastRecordForNotice();
			 $("#noticeTimeDiv").removeAttr("hidden")
			 $("#noticePlayTimeDiv").removeAttr("hidden")
		 }else{
			 memberLastRecordForNotice();
			 $("#noticeTimeDiv").attr("hidden", "hidden");
			 $("#noticePlayTimeDiv").attr("hidden", "hidden");
		 }
	     if (v == 1) {
			 //触发高级记忆功能
			 memberLastRecord();
	         $(".timearea").removeAttr("hidden")
			 //保证定时方式选中的是固定时间
			 $("#timetype1").click();

	     }else{
			 //触发高级记忆功能
			 memberLastRecord();
	         $(".timearea").attr("hidden", "hidden");
	     }
	 }

	 function get_one_broadcast(taskId) {
		let url = httpProto+"://"+host+"/control/20180628/infs/getBroadTaskByTaskId.json";
		let type = "post";
		let param = JSON.stringify({"task_id":taskId});
		if('6' == stype){
			url = httpProto+"://"+host+"/control/offlineTask/getOfflineTaskDetailById.json";
			// url = "http://localhost:8090/control/offlineTask/getOfflineTaskDetailById.json";
			type = "get";
			param = {"bId":taskId};
		}
	     $.ajax({
	         url:url,
			 // url:httpProto+"://"+"localhost:8090"+"/control/20180628/infs/getBroadTaskByTaskId.json",
	         type:type,
	         data:param,
	         dataType:"json",
			 async:false,
	         contentType:"application/json",
	         success:function(data){
	             if (data.statuscode=="000000" || data.code == 200){
					 if(stype == '6'){
						 fullData(data.data);
						 $('#form-data h4').html('修改离线广播任务')
					 }else{
						 fullData(data);
						 $('#form-data h4').html("修改广播任务");
					 }
	                 $("#editModal").modal("show");
	             } else{
	                 $.alert("获取数据出错!");
	             }
	         }
	     })
	 }
	function refreshTree() {
		$("#deptTreeForBroad").treeview({
			data : allDeptData,// 赋值
			showTags:false,
			levels: 99,
			onNodeSelected: function(event, node) {
				$('#deptInputForBroad').val(node.text);
				$('#deptRealIdForBroad').val(node.id);
				$('#deptTreeForBroad').css('display','none')
			},
		});
	}
	function refreshTreeNotice() {
		$("#deptTreeForNotice").treeview({
			data : allDeptData,// 赋值
			showTags:false,
			levels: 99,
			onNodeSelected: function(event, node) {
				$('#deptInputForNotice').val(node.text);
				$('#deptRealIdForNotice').val(node.id);
				$('#deptTreeForNotice').css('display','none')
			},
		});
	}
	function refreshTreeCheck() {
		$("#deptTreeForCheck").treeview({
			data : allDeptData,// 赋值
			showTags:false,
			levels: 99,
			onNodeSelected: function(event, node) {
				$('#deptInputForCheck').val(node.text);
				$('#deptRealIdForCheck').val(node.id);
				$('#deptTreeForCheck').css('display','none')
			},
		});
	}
	var transferBroad = null;
	function initTransfer(data,data1){
		transferBroad = new Transfer()
		//显示搜索框
		transferBroad.render({
			elem: '#transferContainer',
			// 全部数据
			data: data,
			width:400,
			// 已选择数据，默认在右边
			value:data1 ? data1 : [],
			title: ['待选分机', '已选分机'],
			// 是否展示关键词搜索
			showSearch: true,
			// 初始化的所有菜单在 右侧 ,默认 左侧
			isRight:false,
			// 菜单二级全展开
			spread:true
		})
	}
	function log(str,data){
	    if (str == null || str == "") {
	        str = "Data"
	    }
	}

	 function fullData(data){
		 $("#broadcastname").val(data.name)
		 $("#broadcasttime").val(data.lasting_time);
		 $('#taskId').val(data.id)

		 let dept_id = data.dept_id;
		 $("#deptRealIdForBroad").val(dept_id);
		 let dept_name = '' == dept_id || '0' == dept_id ? '全部区域' : '-1' == dept_id ? '仅管理员可见' : data.dept_name;
		 $("#deptInputForBroad").val(dept_name);
		 // $('#deptTreeForBroad').treeview('toggleNodeChecked', [ checkableNodes, { silent: true } ]);
		 var dl = data.part_id;
		 generFromData(dl,"B");
		 if(stype == '6'){
			 set_select_checked("playFileType",data.play_file_type)
			 set_select_checked("playingMode",data.playing_mode)
			 $("#textContent").val(data.text);
			 set_select_checked("musicList",data.audioId)
			 $("#playtimeOffline").val(data.playTime);
			 $("#timetype"+data.timeType).click();
			 if(data.broadcast_time && data.broadcast_time.length > 0){
				 $('#weekTimeOffline').val(data.broadcast_time[0].week_time);
				 data.broadcast_time.forEach(function(v) {
					 $("#checkboxOffline"+v.week_day).prop("checked",true);
				 });
			 }
			 changePlayType();
			 changeTimeArea();
			 changePlayingMode();
			 return;
		 }
		 //文字、文件任务
		 if (data.type === "3") {
			 if (data.type === "3" && data.text_content !== '') {
				 data.play_file_type = '1'//TTS
			 }
			 if (data.audio_id !== '') {//语音
				 data.play_file_type = '2'
			 }
		 }
		 if (data.type === "1") {
			 if (data.text_content !== '') {//文字
				 data.play_file_type = '3'
			 }
		 }
		 set_select_checked("play_file_type",data.play_file_type)
		 changeFileType();
		 set_select_checked("playTimeType",data.play_time_type)
	     set_select_checked("type",data.priority)
	     $("#broadcasttimes").val(data.play_times)
	     $("#broadcasttime").val(data.lasting_time)
	     set_select_checked("broadcastsip",data.capture_dev)
	     set_select_checked("broadcastpstn",data.access_num)
	     set_select_checked("tipsmusic",data.prompt_tone)
	     $("#pstnpassword").val(data.access_num_pw)
	     set_select_checked("broadcasttype",data.type)
	     $("#voice").slider("setValue",data.volume)
	     $("#broadcasttxt").val(data.text_content)
	     set_select_checked("audiolist",data.play_list_id)
	     set_select_checked("audiotype",data.playing_mode)
		 set_select_checked('btype',data.play_type)
		 $('#status').val(data.status)
		 $('#filepath').val(data.text_file)
		 var ttable_data = [];
		 var ttable_holiday_data = [];
		 if (data.play_type==1) {
		 	$(".timearea").removeAttr("hidden")
			var ttype = data.timetype

			$('input[name="timetype"]').each(function(){
				if($(this).val() == ttype){
					$(this).checked
				}
			})

			if(ttype==1){
				$("#timeinput").removeAttr("hidden")
				$("#timetable").attr("hidden","hidden")
				$('#playtime').val(data.playing_time)
				//$("#datepicker").datetimepicker("setDate", new Date())
			}else{
				$("#timetable").removeAttr("hidden")
				$("#timeinput").attr("hidden","hidden")

				ttable_data = produceTimeData(data.broadcast_time)
				ttable_holiday_data = produceHolidayData(data.broadcast_holiday)
			}
		 } else{
		 	$(".timearea").attr("hidden","hidden")
		 }
		 set_select_checked("broadcastVoice",data.audio_id)
	     changeOption(data.type);
		 //生成时间表 
		generTable(ttable_data,0);
		//生成节假日
		generTable(ttable_holiday_data,1);
		//设置是否启用
		//console.log("data:>>> "+JSON.stringify(data))
		$("#b_enable").prop("checked",data.b_enable === '1');
	 }
//id = Date.now() + Math.random().toString(16)
	 function produceTimeData(data){
		 if(data.length<=0){
			 return;
		 }
		 let Mons = [],Tues=[],Weds=[],Thus=[],Fris=[],Sats=[],Suns=[]
		 let max = 0;
		 for(let i = 0; i < data.length; i++){
			 var time = data[i]
			 let weekDay = time.week_day ? time.week_day+"" : time.weekDay+""
			switch (weekDay){
				case '0':
					Mons.push(time)
					break;
				case '1':
					Tues.push(time)
					break;
				case '2':
					Weds.push(time)
					break;
				case '3':
					Thus.push(time)
					break;
				case '4':
					Fris.push(time)
					break;
				case '5':
					Sats.push(time)
					break;
				case '6':
					Suns.push(time)
					break;
				default:
					break;
			}
		 }
		 max = Mons.length
		 if(Tues.length > max){
			 max = Tues.length
		 }
		 if(Weds.length > max){
			 max = Weds.length
		 }
		 if(Thus.length > max){
			 max = Thus.length
		 }
		 if(Fris.length > max){
			 max = Fris.length
		 }
		 if(Sats.length > max){
			 max = Sats.length
		 }
		 if(Suns.length > max){
			 max = Suns.length
		 }
		 var ttableData = []
		 for(let i = 0; i < max; i++){
			 var tt = {'index':i,'Mon':'','Tue':'','Wed':'','Thu':'','Fri':'','Sat':'','Sun':''}
			 ttableData.push(tt)
		 }
		 for(let i = 0; i < Mons.length; i++){
			 ttableData[i].Mon = Mons[i].week_time ? Mons[i].week_time : Mons[i].weekTime
		 }
		 for(let i = 0; i < Tues.length; i++){
			 ttableData[i].Tue = Tues[i].week_time ? Tues[i].week_time : Tues[i].weekTime
		 }
		 for(let i = 0; i < Weds.length; i++){
		 	ttableData[i].Wed = Weds[i].week_time ? Weds[i].week_time : Weds[i].weekTime
		 }
		 for(let i = 0; i < Thus.length; i++){
		 	ttableData[i].Thu = Thus[i].week_time ? Thus[i].week_time : Thus[i].weekTime
		 }
		 for(let i = 0; i < Fris.length; i++){
			ttableData[i].Fri = Fris[i].week_time ? Fris[i].week_time : Fris[i].weekTime
		 }
		 for(let i = 0; i < Sats.length; i++){
		 	ttableData[i].Sat = Sats[i].week_time ? Sats[i].week_time : Sats[i].weekTime
		 }
		 for(let i = 0; i < Suns.length; i++){
		 	ttableData[i].Sun = Suns[i].week_time ? Suns[i].week_time : Suns[i].weekTime
		 }
		 return ttableData

	 }
	 function produceHolidayData(data){
		if(data.length<=0){
			return;
		}	
		var ttableData = data;
		return ttableData

	}
	 function contractArray(data){
	     if (!Array.isArray(data)) {
	         console.log("参数非数组!")
			 return;
	     }
	     var rl = []
	     for (var i = 0; i < data.length; i++) {
	         var str = {"id":data[i], "value": data[i]}
	         rl.push(str)
	     }
	     return rl;
	 }


	 function reduceArray(str1,str2){
	    if (!Array.isArray(str1) || !Array.isArray(str2)){
	        console.log("输入参数非数组!");
			return;
	    }
	    var list = []
	     for (var i = 0; i < str1.length; i++) {
	         for (var j = 0; j < str2.length; j++) {
	             if (str1[i]===str2[j]){
	                 str1.splice(i,1);
	                 list.push(str2[j])
	             }
	         }
	     }
	     return list;
	 }
	 function getOfflineData() {
		 //提交离线任务
		 let newBroad = {};
		 newBroad.task_id = $('#taskId').val();//广播任务ID
		 // newBroad.broadcast_time = this.formatTabelTime(newBroad.broadcast_time)
		 newBroad.sys_user_id = userId;
		 newBroad.dept_id = $('#deptRealIdForBroad').val();
		 if(!newBroad.dept_id){
			 newBroad.dept_id = '1' == isAdmin ? '-1' : deptId;
		 }
		 if (newBroad.temp_part_id !== '-1') {
			 newBroad.part_id = newBroad.temp_part_id
		 }
		 if (newBroad.part_type === '') {
			 newBroad.part_type = '2'
		 }
		 if (newBroad.task_id === '') {
			 newBroad.task_id = newBroad.id
		 }
		 newBroad.type = '6';
		 newBroad.name = $('#broadcastname').val();
		 //验证表单内容
		 if (!newBroad.name) {
			 $.alert('广播名称不能为空')
			 return
		 }
		 newBroad.playing_mode = $('#playingMode option:selected').val();
		 if (!newBroad.playing_mode) {
			 $.alert('播放模式不能为空')
			 return
		 }
		 newBroad.play_file_type = $('#playFileType option:selected').val();
		 newBroad.text_content = $('#textContent').val();
		 let playType = newBroad.play_file_type;
		 if (playType === '3') {
			 newBroad.audio_id = ''
			 newBroad.text_audio_file = ''
			 if (!newBroad.text_content) {
				 $.alert('文字内容不能为空')
				 return
			 }
		 }
		 let musicId = $('#musicList option:selected').val();
		 newBroad.audio_id = musicId;
		 newBroad.text_audio_file = $('#musicInput'+musicId).val();
		 if (playType === '2') {
			 newBroad.text_content = ''
			 if (!newBroad.audio_id || newBroad.audio_id === '-1' || !newBroad.text_audio_file) {
				 $.alert('语音文件不能为空')
				 return
			 }
		 }
		 if (playType === '1') {
			 newBroad.audio_id = ''
			 newBroad.text_audio_file = ''
			 if (!newBroad.text_content) {
				 $.alert('文本文件不能为空')
				 return
			 }
		 }
		 newBroad.lasting_time = $("#broadcasttime").val();
		 if (newBroad.lasting_time === '' && newBroad.playing_mode == '3') {
			 $.alert('播放时长不能为空')
			 return
		 }
		 //定时广播
		 newBroad.play_type = '1';
		 newBroad.playing_time = $('#playtimeOffline').val();
		 newBroad.timetype = $('input[name="timetype"]:checked').val();
		 let week_time = $('#weekTimeOffline').val();
		 if (!week_time && newBroad.timetype === '2') {
			 $.alert('生效时间不能为空')
			 return
		 }
		 let arry = new Array();
		 //循环所有选中的值
		 $('input[name="checkboxOffline"]:checked').each(function(index, element) {
		 	let paramOne = {
				"week_day":$(this).val(),
				"week_time": week_time
			};
			 //追加到数组中
			 arry.push(paramOne);
		 });
		 //将数组元素连接起来转化为字符串
		 newBroad.broadcast_time = arry;
		 if (newBroad.timetype === '1') {
			 if (!newBroad.playing_time) {
				 $.alert('广播时间不能为空')
				 return
			 }
		 } else if (newBroad.timetype === '2') {
			 if (newBroad.broadcast_time.length < 1) {
				 $.alert('每周不能为空')
				 return
			 } else {
				 if (newBroad.broadcast_time[0].week_time === '') {
					 $.alert('生效时间不能为空')
					 return
				 }

			 }
		 }

		 if (newBroad.play_type === '0') {
			 var date = new Date();
			 newBroad.playing_time = dateFormat('YYYY-mm-dd HH:MM:SS',date)
		 }
		 let part_id_arr = transferBroad.getTransferData();
		 let partIds = [];
		 partIds = this.getAllNodeId(partIds, part_id_arr)
		 newBroad.part_id = partIds.toString();
		 if (!newBroad.part_id) {
			 $.alert('请选择分机')
			 return;
		 }
		 newBroad.order_num = '0';
		 return newBroad;
	 }
	 /* 获取数据*/
	 function getData(){
	    //获取Model 数据
		//新增是否启用
		// console.log($("#b_enable").prop("checked"))
		let isChecked = $("#b_enable").prop("checked")
		var b_enable = isChecked ? '1' : '0';
		var task_id = $('#taskId').val();//广播任务ID
		var play_type = $('#btype option:selected').val();
		var status = $('#status').val();
		if(status == null || status == '' || status == undefined){
			status = b_enable;
		}
		var name = $('#broadcastname').val();
		var priority = $("#type option:selected").val();
		if(priority == null || priority == '' || priority == undefined){
			$.alert('请选择优先级')
			return false;
		}
		var play_times = $('#broadcasttimes').val();
		var lasting_time = $('#broadcasttime').val();
		var capture_dev = $('#broadcastsip option:selected').val();
	    var access_num = $("#broadcastpstn option:selected").val();
	    var prompt_tone = $("#tipsmusic option:selected").val();
		var access_num_pw = $("#pstnpassword").val();
	    var play_list_id = $("#audiolist option:selected").val();
	    var type = $('#broadcasttype option:selected').val();
		var volume = $('#voice').slider('getValue');
		var text_content = $('#broadcasttxt').val();
		var play_list_id = $('#audiolist option:selected').val();
		var playing_mode = $('#audiotype option:selected').val();
		var text_file = $('#filepath').val();
		let deptId = $('#deptRealIdForBroad').val();
		var part_id_arr = transferBroad.getTransferData();
		var part_id = "";
		let partIds = [];
		partIds = this.getAllNodeId(partIds, part_id_arr)
		part_id = partIds.toString();
		let play_time_type = $('#playTimeType option:selected').val();
		//播放次数与播放时长不能共存
		 if ('1' == play_time_type) {
			 lasting_time = '0';
		 }else{
			 play_times = '0';
		 }
		 if('2' == type || '1' == type){
			 if (!play_times && '1' == play_time_type) {
				 $.alert('播放次数不能为空')
				 return false;
			 }
			 if (!lasting_time && '0' == play_time_type) {
				 $.alert('播放时长不能为空')
				 return false;
			 }
		 }
		 if('5' == type){
		 	//采播无播放时长类型
			 play_time_type = "";
		 }
	    if(!part_id){
		    $.alert('请选择分机')
		    return false;
	    }
		 //新增播放类型，type当选择文字时为1.选择tts或语音文件时为3.
		 var play_file_type = $("#play_file_type").val();
		 var audio_id = "";
		 let text_audio_file = "";
		 if(play_file_type == '2'){
			 audio_id = $("#broadcastVoice").val();
			 text_audio_file = $('#broadMusicInput'+audio_id).val();
		 }
		 if(type == '1' && '3' != play_file_type){
			 type = '3';
		 }
		if(type == '3' && '1' == play_file_type){//文件广播且选择tts
			if(text_file == null || text_file == ''){
				$.alert('请选择文件')
				return false;
			}
			text_content = text_file
		}
		 if(type == '3' && '2' == play_file_type){//文件广播且选择语音
			 text_content = "";
		 	if(!audio_id || !text_audio_file){
				 $.alert('请选择语音文件')
				return false;
			}
		 }

		//var timetype = $('input[name="timetype"]:checked').val();
		var timetype = '0'

		/* if(play_type != '1'){
			timetype = '0'
		} */
		
			if(play_type!='0'){
				status = '0'
				timetype = $('input[name="timetype"]:checked').val();
			}
		var playing_time = $('#playtime').val();
		var broadcast_time_list = $('#bootstrap-table').bootstrapTable('getData')
		var broadcast_time = []
		for (var i = 0; i < broadcast_time_list.length; i++) {
			var btime = broadcast_time_list[i]
			for(key in btime){
				if(btime[key] != ''){
					if(key == 'Fri'){
						broadcast_time.push({"week_day":"4","week_time":btime[key]})
					}
					if(key == 'Mon'){
						broadcast_time.push({"week_day":"0","week_time":btime[key]})
					}
					if(key == 'Thu'){
						broadcast_time.push({"week_day":"3","week_time":btime[key]})
					}
					if(key == 'Tue'){
						broadcast_time.push({"week_day":"1","week_time":btime[key]})
					}
					if(key == 'Wed'){
						broadcast_time.push({"week_day":"2","week_time":btime[key]})
					}
					if(key == 'Sat'){
						broadcast_time.push({"week_day":"5","week_time":btime[key]})
					}
					if(key == 'Sun'){
						broadcast_time.push({"week_day":"6","week_time":btime[key]})
					}
				}

			}
		}

		volume = ""+volume+""
		if(playing_mode == "" || playing_mode == null){
			playing_mode = '1'
		}
		//节假日时间
		var broadcast_holiday_list = $('#bootstrap-table-holiday').bootstrapTable('getData')
		var broadcast_holiday = []
		for (var i = 0; i < broadcast_holiday_list.length; i++) {
			var btime = broadcast_holiday_list[i]
			broadcast_holiday.push(broadcast_holiday_list[i]);
		}

		//新增version，标注新版本，放止影响老版本的demo
		var data = JSON.stringify({"access_num":access_num,"access_num_pw":access_num_pw,"prompt_tone":prompt_tone,"play_list_id":play_list_id,
		"priority":priority,"capture_dev":capture_dev,"volume":volume,"play_times":play_times ,
		"text_content":text_content,"text_file":text_file,"play_type":play_type,"task_id":task_id,
		"id":task_id,"name":name,"type":type,"timetype":timetype,"playing_mode":playing_mode,"status":status,
		"playing_time":playing_time,"lasting_time":lasting_time,"part_type":"2","part_id":part_id,"sys_user_id":username,"broadcast_time":broadcast_time,
		"play_file_type":play_file_type,"broadcast_holiday":broadcast_holiday,"b_enable":b_enable,"dept_id":deptId,"play_time_type":play_time_type,
			"version":"2.2.5","audio_id":audio_id,"text_audio_file":text_audio_file
		});
		return data;
	 }
	 function getAllNodeId(expandedKeys, moduleDataList) {
		 for (let i = 0; i < moduleDataList.length; i++) {
			 if("0" == moduleDataList[i].isDept){
				 expandedKeys.push(moduleDataList[i].label)
			 }
			 if (moduleDataList[i].children) {
				 expandedKeys = this.getAllNodeId(expandedKeys, moduleDataList[i].children)
			 }
		 }
		 return expandedKeys
	 }
	 function set_select_checked(selectId,checkValue){
	    var select = document.getElementById(selectId)
	     for (var i = 0; i < select.options.length; i++) {
	         if (select.options[i].value == checkValue) {
	             select.options[i].selected = true;
	             break;
	         }
	     }
	 }
	 /* 警报部分*/
	 function getAlarmData(request){
		 $.ajax({
			 url:httpProto+'://'+host+"/control/api_v2.2.5/alarm/query/queryAll.json",
			 type: "post",
			 data:JSON.stringify(request.data),
			 dataType:"json",
			 async:false,
			 headers:{
				 "Authorization":authForAll
			 },
			 contentType:"application/json",
			 success:function(data){
				 if (data.code === 200) {
					 let newData = data.data;
					 processAlarmData(newData.list);
					 request.success({
						 total: newData.totalCount,
						 rows: newData.list
					 })
				 }else{
					 alert('加载数据出错')
				 }
			 }
		 })
	 }

	 function getAlarmDetail(alarmId){
		 if(alarmId == "" || alarmId == null || alarmId == undefined){
			 console.log("参数为空")
			 return
		 }
		 var data = ""
		 $.ajax({
			 url:httpProto+'://'+host+'/control/20180628/infs/detailAlarm.json?alarm_id='+alarmId,
			 dataType:'json',
			 type:'get',
			 async:false,
			// contentType:'application/json',
			 success:function(result){
				 if(result.statuscode == '000000'){
					 data = result.data
				 }
			 }
		 })
		 return data
	 }

	 //搜索数据处理
	 function searchData(data){
		 var alarm_name = $('#name').val();
		 var starttime = $('#starttime').val();
		 var endtime = $('#endtime').val();
		 if(data.length<=0){
			 return;
		 }
		 var param1 = '';
		 var param2 = '';
		 var param3 = '';
		 var d1 = []
		 var d2 = []
		 var d3 = []
		 if(alarm_name != null && alarm_name!=''&&alarm_name != undefined){
			 param1 = alarm_name
		 }
		 if(starttime != null &&　starttime != '' && starttime != undefined){
			 param2 = starttime
		 }
		 if(endtime != null && endtime != '' && endtime != undefined){
			 param3 = endtime
		 }
		 if(param1!=''){
			 for (var i = 0; i < data.length; i++) {
			 	var _element = data[i]
				if(_element.device_name.indexOf(param1) != -1){
					d1.push(_element)
				}
			 }
		 }else{
			 d1 = data
		 }
		 if(param2!='' && d1.length>0){
			 for (var i = 0; i < d1.length; i++) {
			 	var _this = d1[i]
				if(_this.create_date>=param2){
					d2.push(_this)
				}
			 }
		 }else{
			 d2 = d1
		 }
		 if(param3!='' && d2.length>0){
			 for (var i = 0; i < d2.length; i++) {
			 	var _this = d2[i]
				if(_this.create_date <= param3){
					d3.push(_this)
				}
			 }
		 }else{
			 d3 = d2
		 }

		 return d3;
	 }

	 function alarmStatus(status){
	 		 var _status = ''
	 		 switch(status){
	 			 case "1":
	 				_status = '新警报';
	 				break;
	 			case "2":
	 				_status = '已确认';
	 				break;
	 			case "3":
	 				_status = '已解除';
	 				break;
	 			default:
	 				_status = '';
	 				break;
	 		 }
			 return _status;
	 }

	 function alarmLevel(level){
	 		 var _level = ''
	 		 switch(level){
	 			 case "1":
	 				_level = '一级';
	 				break;
	 			case "2":
	 				_level = '二级';
	 				break;
	 			case "3":
	 				_level = '三级';
	 				break;
	 			default:
	 				_level = '';
	 				break;
	 		 }
			 return _level;
	 }
	 //处理字段
	 function processAlarmData(data){
		 if(data.length<=0){
			 return;
		 }
		 for (var i = 0; i < data.length; i++) {
		 	var _this = data[i]
			_this.alarm_level = alarmLevel(_this.alarmLevel)
			_this.status = alarmStatus(_this.status)
		 }

	 }

	 //（预案）广播联动 table
	 function loadBroadcastTable(data){
		 $('#linkageTable').bootstrapTable('destroy');
		 $('#linkageTable').bootstrapTable({
			cache:false,
			data:data,
			clickToSelect:true,
			uniqueId:'id',
			showColumns:false,
			scrollbar:true,
			height:'500px',
			autoHeight: true,
			columns:[{
				checkbox:true
			},{
				field:'id',
				title:'id',
				visible: false
			},{
				field:'extNum',
				title:'广播接入号'
			},{
				field:'broad_name',
				title:'广播名称'
			},{
				field:'broad_type',
				title:'广播类型',
			}]

		})
	 }

	 //（预案）视频联动 table
	 function loadVideoTable(data){
		$('#linkageTable').bootstrapTable('destroy');
		$('#linkageTable').bootstrapTable({
		   cache:false,
		   data:data,
		   clickToSelect:true,
		   uniqueId:'id',
		   showColumns:false,
		   scrollbar:true,
		   height:'500px',
		   autoHeight: true,
		   columns:[{
			   checkbox:true
		   },{
			   field:'id',
			   title:'id',
			   visible: false
		   },{
			   field:'deviceNo',
			   title:'摄像头标识名称'
		   },{
			   field:'brandName',
			   title:'摄像头品牌'
		   },{
			   field:'ip',
			   title:'IP 地址',
		   },{
			   field:'port',
			   title:'端口号'
		   },{
		   	   field:'user',
		   	   title:'初始化帐号',
		   }]

	   })
	}

	//（预案）短信联动 table
	function loadSmsTable(data){
		$('#linkageTable').bootstrapTable('destroy');
		$('#linkageTable').bootstrapTable({
		   cache:false,
		   data:data,
		   clickToSelect:true,
		   uniqueId:'id',
		   showColumns:false,
		   scrollbar:true,
		   height:'500px',
		   autoHeight: true,
		   columns:[{
			   checkbox:true
		   },{
			   field:'id',
			   title:'id',
			   visible: false
		   },{
			   field:'smsNum',
			   title:'短信号码'
		   },{
			   field:'smsText',
			   title:'短信内容'
		   }]

	   })
	}

	//（预案）通知联动 table
	function noticeTable(data){
		$('#linkageTable').bootstrapTable('destroy');
		$('#linkageTable').bootstrapTable({
		   cache:false,
		   data:data,
		   clickToSelect:true,
		   uniqueId:'id',
		   showColumns:false,
		   scrollbar:true,
		   height:'500px',
		   autoHeight: true,
		   columns:[{
			   checkbox:true
		   },{
			   field:'id',
			   title:'id',
			   visible: false 
		   },{
			   field:'notice_num',
			   title:'接入号'
		   },{
			   field:'notice_name',
			   title:'通知名称'
		   }]

	   })
	}

	//（预案）会议联动 table
	function meetingTable(data){
		$('#linkageTable').bootstrapTable('destroy');
		$('#linkageTable').bootstrapTable({
		   cache:false,
		   data:data,
		   clickToSelect:true,
		   uniqueId:'id',
		   showColumns:false,
		   scrollbar:true,
		   height:'500px',
		   autoHeight: true,
		   columns:[{
			   checkbox:true
		   },{
			   field:'id',
			   title:'id',
			   visible: false 
		   },{
			   field:'accessNum',
			   title:'接入号'
		   },{
			   field:'conf_name',
			   title:'会议名称'
		   }]

	   })
	}

	 //（预案）查询【广播，通知，会议，视频，短信，对讲】
	 function getDetailPlanDetails(planId,type){
		var param={'planId':planId};
		$.ajax({
			url:httpProto+'://'+host+'/system-service/api-v1.0/PrePlan/detail/getPrePlanDetailsByPlanId',
    		//开发环境
    		//url:'http://localhost:8080/api-v1.0/PrePlan/detail/getPrePlanDetailsByPlanId',
			type: 'get',
			data:param,
			dataType: 'json',
			contentType:'application/json',
			headers:{
				'Authorization':token
			},
			success:function(res){
          		if (res.code === 200) {
					let broad_link = []
					let video_link = []
					let notice_link = []
					let conf_link = []
					smslink_data=[];
					// console.log(res.data);
					res.data.forEach(item => {
					  switch (item.linkType) {
						case 1:	
						  	broad_link.push(item)
							  break
						case 2:
						  	video_link.push(item)
							  break
						case 3:
						  	smslink_data.push(item)
							  break
						case 4:
							Object.assign(intercom,item)
							$('#intercomExt').val(intercom.extNum);
							  break
						case 5:
							conf_link.push(item)
							  break
						case 6:
							notice_link.push(item)
							  break
					  }
					});

					if(type == 3){
						loadSmsTable(smslink_data);
					}

					// 加载广播数据
					$.ajax({
						url:httpProto+'://'+host+'/control/20180628/infs/getBroadTask.json',
						//开发环境
						//url:'http://localhost:8080/control/20180628/infs/getBroadTask.json',
						type: 'post',
						data:JSON.stringify({type: '', play_type: '', status: '',deptId:deptId,isAdmin:isAdmin}),
						dataType: 'json',
						contentType:'application/json',
						headers:{
							'Authorization':token
						},
						success:function(res){
							let response = res
                			broad_list = []
							broadlink_data= []
                			if (response.statuscode === '000000') {
								if(isAdmin == '1'){
									broad_list = response.data
								}else{
									response.data.forEach(item=>{
								  		if(item.isAdminType == '0'){
											broad_list.push(item);
								  		}
									});
								}
                			    let hasBroad = []
								broad_link.forEach(item => {
									response.data.forEach(it => {
                			      if (item.broadcastId === Number(it.id)) {
                			          hasBroad.push(it)
                			        item.broad_pstn = it.access_num
                			        item.broad_name = it.name
                			        item.broad_type = it.type
                			        item.broad_ty = it.type
									item.broad_id=it.id
                			        broadlink_data.push(item)
                			      }
                			    })
                			  });
                			  //广播去除已使用的
                			    broad_list = diffList(broad_list, hasBroad,'id')
								broadlink_data.forEach(i=>{
									i.broad_type = broadTask(i.broad_type);
								});

								if(type == 1){
									loadBroadcastTable(broadlink_data);
								}
								
                			}
						},
						error:function(){
							console.log('error......')
						}
					}).catch(error=>{
						log('error',error)
					})
					
					// 加载视频数据
					$.ajax({
						url:httpProto+'://'+host+'/video-service/api-v1.0/Camera/queryAllCamera',
						//开发环境
						//url:'http://localhost:8081/api-v1.0/Camera/queryAllCamera',
						type: 'get',
						contentType:'application/json',
						headers:{
							'Authorization':token
						},
						success:function(res){
							let response = res
                    		video_list = []
							videolink_data = []
                    		if (response.code === 200) {
								if(isAdmin == '1'){
									video_list = response.data
								}else{
									response.data.forEach(item=>{
								  		if(item.isAdminType == '0'){
											video_list.push(item);
								  		}
									});
								}
                    		    let hasCamera = []
                    		    video_link.forEach(item=>{
                    		        response.data.forEach(ite=>{
                    		            if (item.cameraId === ite.id) {
                    		                ite.Id = item.Id
                    		                ite.linkType = item.linkType
											ite.video_id=ite.id
                    		                hasCamera.push(ite)
                    		                videolink_data.push(ite)
                    		            }
                    		        })
                    		    })
                    		    video_list = diffList(video_list,hasCamera,'id')
								videolink_data.forEach(item=>{
									if (item.brand === 1) {
										item.brandName = '大华'
									}else if (item.brand === 2) {
										item.brandName = '海康'
									}else if (item.brand === 3) {
										item.brandName = '金三立'
									}else if(item.brand === 4){
									  	item.brandName = '其他'
									}else if (item.brand === 5) {
									  	item.brandName = '方位'
									}
								})
								if(type == 2){
									loadVideoTable(videolink_data);
								}
                    		}
						},
						error:function(){
							console.log('error......')
						}
					}).catch(error=>{
						log('error',error)
					})

					// 加载通知数据
					$.ajax({
						url:httpProto+'://'+host+'/control/api-v2.2.3/20180628/infs/getCallOutTaskList.json',
						//开发环境
						//url:'http://localhost:8080/control/api-v2.2.3/20180628/infs/getCallOutTaskList.json',
						type: 'post',
						data:JSON.stringify({ notice_type: '', type: '0'}),
						dataType: 'json',
						contentType:'application/json',
						headers:{
							'Authorization':token
						},
						success:function(res){
							let response = res
                			notice_list = []
							noticelink_data= []
                			if (response.code == 200) {
								if(isAdmin == '1'){
									notice_list = response.data
								}else{
									response.data.forEach(item=>{
								  		if(item.isAdminType == '0'){
											notice_list.push(item);
								  		}
									});
								}
                			    let hasBroad = []
								notice_link.forEach(item => {
									response.data.forEach(it => {
                			      if (item.broadcastId === Number(it.id)) {
                			          hasBroad.push(it)
                			        item.notice_num = it.access_num
                			        item.notice_name = it.name
									item.notice_id = it.id
                			        noticelink_data.push(item)
                			      }
                			    })
                			  });
							  	notice_list = diffList(notice_list, hasBroad,'id')
								if(type == 6){
									noticeTable(noticelink_data);
								}
                			}
						},
						error:function(){
							console.log('error......')
						}
					}).catch(error=>{
						log('error',error)
					})

					// 加载会议数据
					$.ajax({
						url:httpProto+'://'+host+'/control/api_v2.2.5/conference/query/queryAllForNoPage.json',
						//开发环境
						//url:'http://localhost:8080/control/api_v2.2.5/conference/query/queryAllForNoPage.json',
						type: 'post',
						contentType:'application/json',
						data:JSON.stringify({userId:userId}),
						headers:{
							'Authorization':authForAll
						},
						success:function(res){
							let response = res
							conf_list = []
							conflink_data = []
							if (response.code === 200) {
								if(isAdmin == '1'){
									conf_list = response.data
								}else{
									response.data.forEach(item=>{
								  		if(item.isAdminType == '0'){
											conf_list.push(item);
								  		}
									});
								}
								let hasCamera = []
								conf_link.forEach(item=>{
									response.data.forEach(it=>{
										if (item.broadcastId === it.id) {
											hasCamera.push(it)
											item.conf_id=it.id
											item.conf_name=it.name
											item.accessNum = it.accessNum
											conflink_data.push(item)
										}
									})
								})
								conf_list = diffList(conf_list,hasCamera,'id')
								if(type == 5){
									meetingTable(conflink_data);
								}
							}
						},
						error:function(){
							console.log('error......')
						}
					}).catch(error=>{
						log('error',error)
					})
          		}
			},
			error:function(){
				console.log('error......')
			}
		}).catch(error=>{
			log('error',error)
		})
	 }

	 //（预案）联动=>呼叫联动=>确认
	 $('.intercomConfirm').click(function(){
		var extNum = $('#intercomExt').val();
		intercom.extNum=extNum;
		intercom.linkType=4;
		updateDetailActionPlan(intercom);
	 });
	 /*广播类型*/
	 function broadTask(num){
	   switch (num) {
		 case '1':
		   return '文字任务'
		 case '2':
		   return '音乐任务'
		 case '3'://file_broad 合并
		   return '文字任务'
		 case '4':
		   return '喊话任务'
		 case '5':
		   return '采播任务'
		 default:
		   return ''
	   }
	 }

	 function diffList(arr1,arr2,key){
		let clone = arr1.slice(0)
		for (let i = 0; i < arr2.length; i++) {
		  let temp = arr2[i]
		  for (let j = 0; j < clone.length; j++) {
			if (temp[key] === clone[j][key]) {
			  clone.splice(j,1)
			}
		  }
		}
		return uniqueArray(clone,key)
	 }

	 //（预案）table
	 function loadActionPlanTable(){
		$('#alarmtable').bootstrapTable('destroy');
		$('#alarmtable').bootstrapTable({
			cache:false,
			data:'',
			clickToSelect:true,
			uniqueId:'id',
			showColumns:false,
			scrollbar:true,
			height:'500px',
			autoHeight: true,
			ajax:getAllActionPlan,
			queryParams : function (params) {
				//这里的是搜索条件
				let temp = {
					alarmType:planType,
					devName:$("#employeeName-query").val(),
					ext:$("#ext-query").val(),
					isActive:$("#active-query option:selected").val(),
					userId:userId,
					currPage:(params.offset / params.limit) + 1,
					pageLimit:params.limit,
				};
				return temp;
			},
			pagination: true,
			pageNumber:1,
			sidePagination:'server',
			pageSize:10,
			pageList:[10, 20, 50, 100],
				columns:[{
					checkbox:true
				},{
					field:'id',
					title:'id',
					visible: false 
				},{
					field:'devName',
					title:'终端/摄像头名称'
				},{
					field:'deptName',
					title:'分区/端口'
				},{
					field:'alarmType',
					title:'报警类型',
				},{
					field:'isActive',
					title:'触发模式',
				},{
					field:'status',
					title:'状态',
				},{
					field:'activeTime',
					title:'开始时间',
				},{
					field:'ext',
					title:'分机号',
				}]

			})

	 }

	 //（报警）table
	 function loadAlarmTable(){
		 $('#alarmtable').bootstrapTable('destroy');
		 $('#alarmtable').bootstrapTable({
			 cache:false,
			 data:'',
			 clickToSelect:true,
			 uniqueId:'id',
			 showColumns:false,
			 scrollbar:true,
			 search:false,
			 height:'500px',
			 autoHeight: true,
			 ajax:getAlarmData,
			 queryParams : function (params) {
				 //这里的是搜索条件
				 let temp = {
					 type:queryType,//左侧列表点击，为1时查询新报警、已确认报警
					 alarmLevel:$("#alarmLevel option:selected").val(),
					 deviceName:$("#searchAlarmName").val(),
					 deviceNo:$("#searchAlarmSource").val(),
					 remarks:"",//备注
					 status:$("#alarmState option:selected").val(),//单独在queryType为1时进行分区新报警、已确认报警
					 createTimeBegin:"",//发生时间开始
					 createTimeEnd:"",//发生时间结束
					 clearTimeBegin:"",//解除时间开始
					 clearTimeEnd:"",//解除时间结束
					 userId:userId,
					 currPage:(params.offset / params.limit) + 1,
					 pageLimit:params.limit,
				 };
				 return temp;
			 },
			 pagination: true,
			 pageNumber:1,
			 sidePagination:'server',
			 pageSize:10,
			 pageList:[10, 20, 50, 100],
			 columns:[{
			 		checkbox:true
			 	},{
			 		field:'deviceName',
			 		title:'设备名称'
			 	},{
			 		field:'alarm_level',
			 		title:'报警级别'
			 	},{
			 		field:'deviceNo',
			 		title:'报警源',
			 	},{
			 		field:'status',
			 		title:'报警状态',
			 	},{
			 		field:'createDate',
			 		title:'发生时间',
			 	},{
			 		field:'alarmClearDate',
			 		title:'解除时间'
			 	},{
			 		field:'remarks',
			 		title:'备注'
			 	}]
		 })
		 var contentHeight = getVisible();
		 var toolBarH = $('.fixed-table-toolbar').height();
		 var height = contentHeight - toolBarH -131;
		 var container = $('.fixed-table-container').css({'height':height})
	 }

	 //（预案）联动中的条件查询
	 $('.broadcast-query').click(function(){
		var type = $('.nav-tabs .active a').html();
		var condition = $('#linkage-condition').val();
		var value = $('#linkage-value').val();

		switch(type){
			case '广播联动':
				broadlinkQuery(condition,value);
				break
			case '通知联动':
				noticelinkQuery(condition,value);
				break
			case '会议联动':
				break
			case '视频联动':
				videolinkQuery(condition,value);
				break
			case '短信联动':
				smslinkQuery(condition,value);
				break
			default:
				break
		}

	 });

	 function noticelinkQuery(condition,value){
		if(data == ''){
			noticeTable(noticelink_data);
			return;		
		}
		 var data=[];
		 noticelink_data.forEach(item=>{
			if(condition == 1 && item.notice_num.indexOf(value) != -1){
				data.push(item);
			}else if(condition == 2 && item.notice_name.indexOf(value) != -1){
				data.push(item);
			}
			
		})
		noticeTable(data);
	 }

	 function smslinkQuery(condition,value){
		if(data == ''){
			loadSmsTable(smslink_data);
			return;		
		}
		 var data=[];
		 smslink_data.forEach(item=>{
			if(condition == 1 && item.smsNum.indexOf(value) != -1){
				data.push(item);
			}else if(condition == 2 && item.smsText.indexOf(value) != -1){
				data.push(item);
			}
			
		})
		loadSmsTable(data);
	 }

	 function videolinkQuery(condition,value){
		if(data == ''){
			loadVideoTable(videolink_data);
			return;		
		}
		 var data=[];
		 videolink_data.forEach(item=>{
			if(condition == 1 && item.deviceNo.indexOf(value) != -1){
				data.push(item);
			}else if(condition == 2 && item.brandName.indexOf(value) != -1){
				data.push(item);
			}else if(condition == 3 && item.ip.indexOf(value) != -1){
				data.push(item);
			}else if(condition == 4 && item.port.indexOf(value) != -1){
				data.push(item);
			}else if(condition == 5 && item.user.indexOf(value) != -1){
				data.push(item);
			}
			
		})
		loadVideoTable(data);
	 }

	 function broadlinkQuery(condition,value){
		if(data == ''){
			loadBroadcastTable(broadlink_data);
			return;		
		}
		 var data=[];
		broadlink_data.forEach(item=>{
			if(condition == 1 && item.extNum.indexOf(value) != -1){
				data.push(item);
			}else if(condition == 2 && item.broad_name.indexOf(value) != -1){
				data.push(item);
			}else if(condition == 3 && item.broad_type.indexOf(value) != -1){
				data.push(item);
			}
			
		})
		loadBroadcastTable(data);
	 }

	 //（预案）联动窗口关闭时触发
	 $('#linkage').on('hidden.bs.modal', function () {
		$('.nav-tabs li').removeClass();
		$('.nav-tabs li:first').addClass('active');
		$('#broadcastLinkage').removeClass();
		$('#broadcastLinkage').addClass('tab-pane active');
		$('#intercomLinkage').removeClass();
		$('#intercomLinkage').addClass('tab-pane');
	 })

	 //（预案）添加编辑窗口关闭时触发
	 $('#reserveplan').on('hidden.bs.modal', function () {
		$('#planId').val('');
		$('#alarmType').val('1');
		$('#deptName').val('');
		$('#ext').val('');
		$('#isActive').val('0');

		$('#camera').css('display','none');
		$('[for=camera]').attr('hidden','hidden');
		$('#ext').attr('type','text');
		$('[for=ext]').removeAttr('hidden');
		$('#deptName').attr('type','text');
		$('[for=deptName]').removeAttr('hidden');
		$('#employeeId').css('display','');
		$('[for=employeeId]').removeAttr('hidden');
		$('#alarm-deptName').css('display','none');
		employeeAndAlarm(1);

		$('#reserveplan').modal('hide');
	 })
	 
	 //（预案）联动【添加】
	$(".link-add").click(function(){
		var type = $('.nav-tabs .active a').html();
		switch(type){
			case '广播联动':
				$('#reserveLink h4').html("添加广播联动");
				$('#reserveLink-select').removeAttr('hidden')
				$('#reserveLink-input').attr('hidden','hidden');
				$('#reserveLink-select label').html('广播名称:');
				var html='';
				try {
					if(broad_list.length>0){
						broad_list.forEach(item=>{
							html+='<option value="'+item.id+'">'+item.name+'</option>';
						});
					}
				} catch (error) {
					
				}
				
				$('#reserveLink-select select').html(`<option style='display: none;'>请选择广播</option>${html}`);
				break
			case '通知联动':
				$('#reserveLink h4').html("添加通知联动");
				$('#reserveLink-select').removeAttr('hidden')
				$('#reserveLink-input').attr('hidden','hidden');
				$('#reserveLink-select label').html('通知名称:');
				var html='';
				try {
					if(notice_list.length>0){
						notice_list.forEach(item=>{
							html+='<option value="'+item.id+'">'+item.name+'</option>';
						});
					}
				} catch (error) {
					
				}
				
				$('#reserveLink-select select').html(`<option style='display: none;'>请选择通知名称</option>${html}`);
				break
			case '会议联动':
				$('#reserveLink h4').html("添加会议联动");
				$('#reserveLink-select').removeAttr('hidden')
				$('#reserveLink-input').attr('hidden','hidden');
				$('#reserveLink-select label').html('会议名称:');

				var html='';
				try {
					if(conf_list.length>0){
						conf_list.forEach(item=>{
							html+='<option value="'+item.id+'">'+item.name+'</option>';
						});
					}
				} catch (error) {
				}
				$('#reserveLink-select select').html(`<option style='display: none;'>请选择会议室</option>${html}`);
				break
			case '视频联动':
				$('#reserveLink h4').html("添加视频联动");
				$('#reserveLink-select').removeAttr('hidden')
				$('#reserveLink-input').attr('hidden','hidden');
				$('#reserveLink-select label').html('摄像头标识名称:');
				
				var html='';
				try {
					if(video_list.length>0){
						video_list.forEach(item=>{
							html+='<option value="'+item.id+'">'+item.deviceNo+'</option>';
						});
					}
				} catch (error) {
					
				}
				
				$('#reserveLink-select select').html(`<option style='display: none;'>请选择摄像头</option>${html}`);
				break
			case '短信联动':
				$('#reserveLink h4').html("添加短信联动");
				$('#reserveLink-select').attr('hidden','hidden');
				$('#reserveLink-input').removeAttr('hidden')
				break
			default:
				break
		}
		$('#reserveLink').modal('show');
	});

	//（预案）联动【编辑】
	$(".link-edit").click(function(){
		var type = $('.nav-tabs .active a').html();
		var row = $("#linkageTable").bootstrapTable('getSelections')
		if(row.length > 1 || row.length <= 0){
			$.alert('请选择一条'+type)
			return;
		}

		switch(type){
			case '广播联动':
				$('#reserveLink h4').html("编辑广播联动");
				$('#reserveLink-select').removeAttr('hidden')
				$('#reserveLink-input').attr('hidden','hidden');
				$('#reserveLink-select label').html('广播名称:');
				var html='';
				try {
					if(broad_list.length>0){
						broad_list.forEach(item=>{
							html+='<option value="'+item.id+'">'+item.name+'</option>';
						});
					}
				} catch (error) {
					
				}
				$('#reserveLink-select select').html(`<option value="${row[0].broad_id}">${row[0].broad_name}</option>${html}`);
				
				break
			case '通知联动':
				$('#reserveLink h4').html("编辑通知联动");
				$('#reserveLink-select').removeAttr('hidden')
				$('#reserveLink-input').attr('hidden','hidden');
				$('#reserveLink-select label').html('通知名称:');
				var html='';
				try {
					if(notice_list.length>0){
						notice_list.forEach(item=>{
							html+='<option value="'+item.id+'">'+item.name+'</option>';
						});
					}
				} catch (error) {
					
				}
				$('#reserveLink-select select').html(`<option value="${row[0].notice_id}">${row[0].notice_name}</option>${html}`);

				break
			case '会议联动':
				$('#reserveLink h4').html("编辑会议联动");
				$('#reserveLink-select').removeAttr('hidden')
				$('#reserveLink-input').attr('hidden','hidden');
				$('#reserveLink-select label').html('会议名称:');
				var html='';
				try {
					if(conf_list.length>0){
						conf_list.forEach(item=>{
							html+='<option value="'+item.id+'">'+item.name+'</option>';
						});
					}
				} catch (error) {

				}
				$('#reserveLink-select select').html(`<option value="${row[0].conf_id}">${row[0].conf_name}</option>${html}`);
				break
			case '视频联动':
				$('#reserveLink h4').html("编辑视频联动");
				$('#reserveLink-select').removeAttr('hidden')
				$('#reserveLink-input').attr('hidden','hidden');
				$('#reserveLink-select label').html('摄像头标识名称:');
				
				var html='';
				try {
					if(video_list.length>0){
						video_list.forEach(item=>{
							html+='<option value="'+item.id+'">'+item.deviceNo+'</option>';
						});
					}
				} catch (error) {
					
				}
				
				$('#reserveLink-select select').html(`<option value="${row[0].video_id}">${row[0].deviceNo}</option>${html}`);
				break
			case '短信联动':
				$('#reserveLink h4').html("编辑短信联动");
				$('#reserveLink-select').attr('hidden','hidden');
				$('#reserveLink-input').removeAttr('hidden')

				$('#reserveLink-input input').eq(0).val(row[0].smsNum);
				$('#reserveLink-input input').eq(1).val(row[0].smsText);

				break
			default:
				break
		}
		$('#reserveLink').modal('show');
	});

	//（预案）联动添加，编辑取消按钮
	$('.reserveLink-submit-cancel').click(function(){
		$('#reserveLink').modal('hide');
	});

	//（预案）联动添加，编辑确认按钮
	$('.reserveLink-submit-confirm').click(function(){
		var type = $('#reserveLink h4').html();
		var value = $('#reserveLink-select select').val();
		var smsNum = $('#reserveLink-input input').eq(0).val();
		var smsText = $('#reserveLink-input input').eq(1).val();
		var row = $("#linkageTable").bootstrapTable('getSelections')
		if(type != '编辑短信联动' && type != '添加短信联动'){
			if(value.indexOf('请选择') != -1){
				$.alert(value);
				return
			}
		}else{
			if(smsNum == ''){
				$.alert('请输入短信号码');
				return
			}else if(smsText==''){
				$.alert('请输入短信内容');
				return
			}
		}
		var row2 = $("#alarmtable").bootstrapTable('getSelections')
		var param={Id: "",broadcastId: "",cameraId: "",extNum: "",linkType: 0,ppId: row2[0].id,smsNum: "",smsText: ""};
		switch(type){
			case '添加广播联动':
				
				param.linkType=1;
				param.broadcastId=value;

				break
			case '添加通知联动':

				param.linkType=6;
				param.broadcastId=value;
				
				break
			case '添加会议联动':
				param.linkType=5;
				param.broadcastId=value;
				break
			case '添加视频联动':
				
				param.linkType=2;
				param.cameraId=value;

				break
			case '添加短信联动':
				
				param.linkType=3;
				param.smsNum=smsNum;
				param.smsText=smsText;

				break
			case '编辑广播联动':
				
				param.linkType=1;
				param.broadcastId=value;
				param.Id=row[0].id

				break
			case '编辑通知联动':
				
				param.linkType=6;
				param.broadcastId=value;
				param.Id=row[0].id

				break
			case '编辑会议联动':
				param.linkType=5;
				param.broadcastId=value;
				param.Id=row[0].id
				break
			case '编辑视频联动':
				
				param.linkType=2;
				param.cameraId=value;
				param.Id=row[0].id

				break
			case '编辑短信联动':
				
				param.linkType=3;
				param.smsNum=smsNum;
				param.smsText=smsText;
				param.Id=row[0].id

				break
			default:
				break
		}

		//console.log(param);
		if(param.Id == ''){
			addDetailActionPlan(param);
		}else{
			updateDetailActionPlan(param);
		}
		
	});

	/**
	 * 预案=>联动=>编辑
	 */
	 function updateDetailActionPlan(param){
		$.ajax({
			url:httpProto+'://'+host+'/system-service/api-v1.0/PrePlan/detail/updatePrePlanDetail',
    		//开发环境
    		//url:'http://localhost:8080/api-v1.0/PrePlan/detail/updatePrePlanDetail',
			type: 'post',
			data:JSON.stringify(param),
			dataType: 'json',
			contentType:'application/json',
			headers:{
				'Authorization':token,
				'Menu_id':'10801',
      			'Sysuser_id':sysUserId,
      			'Journal_title':encodeURIComponent('${i18n.preplan2}=>${i18n.linkage}=>${i18n.edit}')
			},
			success:function(res){
				let response = res
				if (response.code === 200) {
					var row = $("#alarmtable").bootstrapTable('getSelections')
					getDetailPlanDetails(row[0].id,param.linkType);
					$.alert('编辑成功');
				} else {
					$.alert('编辑失败');
				}
				$('#reserveLink').modal('hide');
			},
			error:function(){
				$.alert('编辑失败');
				$('#reserveLink').modal('hide');
			}
		}).catch(error=>{
			log('error',error)
		})
	}


	/**
	 * 预案=>联动=>添加
	 */
	function addDetailActionPlan(param){
		$.ajax({
			url:httpProto+'://'+host+'/system-service/api-v1.0/PrePlan/detail/addPrePlanDetail',
    		//开发环境
    		//url:'http://localhost:8080/api-v1.0/PrePlan/detail/addPrePlanDetail',
			type: 'post',
			data:JSON.stringify(param),
			dataType: 'json',
			contentType:'application/json',
			headers:{
				'Authorization':token,
				'Menu_id':'10801',
      			'Sysuser_id':sysUserId,
      			'Journal_title':encodeURIComponent('${i18n.preplan2}=>${i18n.linkage}=>${i18n.add}')
			},
			success:function(res){
				let response = res
				if (response.code === 200) {
					var row = $("#alarmtable").bootstrapTable('getSelections')
					getDetailPlanDetails(row[0].id,param.linkType);
					$.alert('添加成功');
				} else {
					$.alert('添加失败');
				}
				$('#reserveLink').modal('hide');
			},
			error:function(){
				$.alert('添加失败');
				$('#reserveLink').modal('hide');
			}
		}).catch(error=>{
			log('error',error)
		})
	}
	
	//（预案）联动【删除】
	$(".link-remove").click(function(){
		var type = $('.nav-tabs .active a').html();
		var row2 = $("#alarmtable").bootstrapTable('getSelections')
		var row = $("#linkageTable").bootstrapTable('getSelections')
		if(row.length > 1 || row.length <= 0){
			$.alert('请选择一条'+type)
			return;
		}
		var text ='';
		var linkType=0;
		switch(type){
			case '广播联动':
				text=row[0].broad_name
				linkType=1;
				break
			case '通知联动':
				text=row[0].notice_name
				linkType=6;
				break
			case '会议联动':
				text=row[0].conf_name
				linkType=5;
				break
			case '视频联动':
				linkType=2;
				text=row[0].deviceNo
				break
			case '短信联动':
				linkType=3;
				text=row[0].smsNum
				break
			default:
				break
		}
		$.confirm({
			title:'删除'+type,
			content:type+' : '+text,
			buttons:{
				确认:function (){
					var param = {ppId:row2[0].id,id:row[0].id,linkType:linkType};
					//console.log(param)
					deleteDetailActionPlan(param);
				},
				取消:function(){}
			}
		})

	});

	/**
	 * 预案=>联动=>删除
	 */
	 function deleteDetailActionPlan(param){
		$.ajax({
			url:httpProto+'://'+host+'/system-service/api-v1.0/PrePlan/detail/deletePrePlanDetail',
    		//开发环境
    		//url:'http://localhost:8080/api-v1.0/PrePlan/detail/deletePrePlanDetail',
			type: 'post',
			data:JSON.stringify(param),
			dataType: 'json',
			contentType:'application/json',
			headers:{
				'Authorization':token,
				'Menu_id':'10801',
      			'Sysuser_id':sysUserId,
      			'Journal_title':encodeURIComponent('${i18n.preplan2}=>${i18n.linkage}=>${i18n.delete}')
			},
			success:function(res){
				let response = res
				if (response.code === 200) {
					var row = $("#alarmtable").bootstrapTable('getSelections')
					getDetailPlanDetails(row[0].id,param.linkType);
					$.alert('删除成功');
				} else {
					$.alert('删除失败');
				}
				$('#reserveLink').modal('hide');
			},
			error:function(){
				$.alert('删除失败');
				$('#reserveLink').modal('hide');
			}
		}).catch(error=>{
			log('error',error)
		})
	}

	 //（预案）联动tab切换
	 function clickLinkage(type){
		 var html='';
		if(type == 1){
			html=`<option value="1">广播接入号</option>
			<option value="2">广播名称</option>
			<option value="3">广播类型</option>`;
			loadBroadcastTable(broadlink_data);
		}else if(type == 2){
			html=`<option value="1">接入号</option>
			<option value="2">通知名称</option>`;
			noticeTable(noticelink_data);
		}else if(type == 3){
			html=`<option value="1">接入号</option>
			<option value="2">会议名称</option>`;
			meetingTable(conflink_data);
		}else if(type == 4){
			html=`<option value="1">摄像头标识名称</option>
			<option value="2">摄像头品牌</option>
			<option value="3">IP 地址</option>
			<option value="4">端口号</option>
			<option value="5">初始化帐号</option>`;
			loadVideoTable(videolink_data);
		}else if(type == 5){
			html=`<option value="1">短信号码</option>
			<option value="2">短信内容</option>`;
			loadSmsTable(smslink_data);
		}

		$('#linkage-condition').html(html);
	 }

	//（预案）联动
	$('.linkage-btn').click(function(){
		var row = $("#alarmtable").bootstrapTable('getSelections')
		if(row.length > 1 || row.length <= 0){
			$.alert('请选择一条预案')
			return;
		}
		getDetailPlanDetails(row[0].id,1);
		$('#linkage').modal('show');
	});

	//（预案）添加
	$('.reservePlan-btn').click(function(){
		$('#planId').val('');
		$('#reserveplan').modal('show');
		$('#reserveplan h4').html("添加预案");
		getDeviceListByUser();
	});

	//（预案）编辑
	$('.reservePlan2-btn').click(function(){
		var row = $("#alarmtable").bootstrapTable('getSelections')
		if(row.length > 1 || row.length <= 0){
			$.alert('请选择一条预案')
			return;
		}

		$('#reserveplan').modal('show');
		$('#reserveplan h4').html("修改预案");
		getDeviceListByUser();
		getActionPlanById(row[0].id);
	});

	//（预案）删除
	$('.removePlan-btn').click(function(){
		var row = $("#alarmtable").bootstrapTable('getSelections')
		if(row.length > 1 || row.length <= 0){
			$.alert('请选择一条预案')
			return;
		}
		$.confirm({
			title:'删除预案',
			content:'预案 : '+row[0].id,
			buttons:{
				确认:async function (){
					var param = {id:row[0].id,devName:row[0].devName};
					deleteActionPlan(param);
				},
				取消:function(){}
			}
		})
		
	});

	//（预案）添加取消按钮
	$('.action-submit-add').click(function(){
		$('#planId').val('');
		$('#alarmType').val('1');
		$('#deptName').val('');
		$('#ext').val('');
		$('#isActive').val('0');

		$('#camera').css('display','none');
		$('[for=camera]').attr('hidden','hidden');
		$('#ext').attr('type','text');
		$('[for=ext]').removeAttr('hidden');
		$('#deptName').attr('type','text');
		$('[for=deptName]').removeAttr('hidden');
		$('#employeeId').css('display','');
		$('[for=employeeId]').removeAttr('hidden');
		$('#alarm-deptName').css('display','none');
		employeeAndAlarm(1);

		$('#reserveplan').modal('hide');
	});

	//（预案）添加确认按钮
	$('.action-submit-edit').click(function(){
		var id = $("#planId").val();//id
		var alarmType = $("#alarmType").val();//报警类型
		var employeeId = $("#employeeId").val();//终端id
		var devName= $("#employeeId option:selected").text();//终端名称
		var deptId = $('#deptId').val();//分区ID
		//var deptId = $("#deptName").val();//分区端口
		var portId = $("#alarm-deptName").val();//分区端口
		var ext = $("#ext").val();//分机号
		var camera= $("#camera").val();//摄像头
		var cameraName= $("#camera option:selected").text();//摄像头
		var isActive = $("#isActive").val();//触发模式

		if(alarmType == 1 || alarmType == 2){
			portId='';
		}else if(alarmType == 4 || alarmType == 5){
			portId='';
			deptId='-1';
			ext='';
			employeeId=camera;
			devName=cameraName;
		}else if(alarmType == 3){
			if(portId != null){
				portId=1;
			}
			var devices = alarmDevices.find(item=>item.id==employeeId);
			ext=devices.num;
			deptId='0';
		}

		if(devName == '请选择终端'){
			$.alert('终端不能为空');
			return;
		}else if(devName == '请选择摄像头'){
			$.alert('摄像头不能为空');
			return;
		}

		var param={
			alarmType:parseInt(alarmType),
			devName:devName,
			employeeId:parseInt(employeeId),
			deptId:parseInt(deptId),
			ext:ext==''?'':parseInt(ext),
			id:id,
			isActive:parseInt(isActive),
			language: "zh-CN",
			portId:portId,
			descr:''
		};
		if(portId == null){
			delete param.portId
		}
		//console.log(param);
		if(id != ''){
			updateActionPlan(param)
		}else{
			addActionPlan(param)
		}
		
	});

	/**
	 *（预案）编辑
	 *
	 */
	 function updateActionPlan(param){
		$.ajax({
			url:httpProto+'://'+host+'/system-service/api-v1.0/PrePlan/updatePrePlan',
    		//开发环境
    		//url:'http://localhost:8080/api-v1.0/PrePlan/updatePrePlan',
			type: 'post',
			data:JSON.stringify(param),
			dataType: 'json',
			contentType:'application/json',
			headers:{
				'Authorization':token,
				'Menu_id':'10803',
      			'Sysuser_id':sysUserId,
      			'Journal_title':encodeURIComponent('${i18n.preplan2}=>${i18n.edit}')
			},
			success:function(res){
				let response = res
				if (response.code === 200) {
					loadActionPlanTable();
					$.alert('成功');
				} else {
				  if (response.msg === '预案已存在') {
					$.alert('预案已存在');
				  } else {
					$.alert('编辑失败');
				  }
				}
				$('#reserveplan').modal('hide');
			},
			error:function(){
				$.alert('编辑失败');
				$('#reserveplan').modal('hide');
			}
		}).catch(error=>{
			log('error',error)
		})
	}

	/**
	 *（预案）删除 
	 *
	 */
	function deleteActionPlan(param){
		$.ajax({
			url:httpProto+'://'+host+'/system-service/api-v1.0/PrePlan/deletePrePlan',
    		//开发环境
    		//url:'http://localhost:8080/api-v1.0/PrePlan/deletePrePlan',
			type: 'post',
			data:JSON.stringify(param),
			dataType: 'json',
			contentType:'application/json',
			headers:{
				'Authorization':token,
				'Menu_id':'10011',
      			'Sysuser_id':sysUserId,
      			'Journal_title':encodeURIComponent('${i18n.preplan2}=>${i18n.delete}')
			},
			success:function(res){
				let response = res
				if (response.code === 200) {
					loadActionPlanTable();
				}
				$('#reserveplan').modal('hide');
			},
			error:function(){
				console.log('error......')
			}
		}).catch(error=>{
			log('error',error)
		})
	}
	//执行预案
	function doTriggerPlan(row){
		let ext = row.ext;
		let alarm_data = "";
		let exten = row.ext
		let type = row.alarmType+"";
		switch (type) {
			case '防拆报警':
				type = "1";
				break
			case '一键报警':
				type = "2";
				break
			case '网关报警':
				type = "3";
				break
			case '移动报警':
				type = "4";
				break
			case '安全帽报警':
				type = "5";
				break
		}
		let cameraAlarm = '0'
		let videoAlarm = '0'
		if (type === '4' || type === '5' ) {
			cameraAlarm = '1'
			videoAlarm = '1'
			ext = row.employeeId;
		}
		if (type === '3') {
			cameraAlarm = '1'
			alarm_data = row.portId;
		}
		method = 'alarm_send'
		let msg = "'alert_type':'"+type+"','ext':'"+ext+"','alarm_data':'"+alarm_data+"'";
		send(msg);
		//添加操作日志
		$.ajax({
			url:httpProto+'://'+host+'/system-service/api-v1.0/PrePlan/addPrePlanStatusLog',
			//开发环境
			//url:'http://localhost:8080/api-v1.0/PrePlan/deletePrePlan',
			type: 'post',
			data:JSON.stringify({status:'1',planId:row.id}),
			dataType: 'json',
			contentType:'application/json',
			headers:{
				'Authorization':token,
				'Menu_id':'10805',
				'Sysuser_id':sysUserId,
				'Journal_title':encodeURIComponent('${i18n.preplan2}=>${i18n.trigger_plan}')
			},
		}).catch(error=>{log('error',error)})
		//查询视频
		$.ajax({
			url:httpProto+'://'+host+'/system-service/api-v1.0/PrePlan/getVideoForTrigger',
			//开发环境
			//url:'http://localhost:8080/api-v1.0/PrePlan/deletePrePlan',
			type: 'get',
			data: {exten:ext,type:type,cameraAlarm:videoAlarm},
			dataType: 'json',
			contentType:'application/json',
			headers:{
				'Authorization':token,
			},
			success:function(res){
				let response = res
				if (response.code === 200) {
					if (response.data.length > 0) {
						var cameraIds = ''
						for (let i = 0; i < response.data.length; i++) {
							cameraIds = cameraIds + response.data[i].cameraId + ','
						}
						cameraIds = cameraIds.substring(0, cameraIds.length - 1)
						$.ajax({
							url:httpProto+'://'+host+'/video-service/api-v1.0/Camera/queryRTMPByExten',
							//开发环境
							//url:'http://localhost:8080/api-v1.0/PrePlan/deletePrePlan',
							type: 'get',
							data: {exten:ext, cameraIds:cameraIds, type:'2', userName:sysUserId,cameraAlarm:cameraAlarm},
							dataType: 'json',
							contentType:'application/json',
							headers:{
								'Authorization':token,
							},
							timeout: 54000,
							success:function(res){
								let response = res
								if (response.code === 200) {
									let data = response.data
									if (data.length > 0) {
										videoModal(data)
										//提示弹出视频 TODO
									}
								}
							},
						}).catch(error=>{
							log('error',error)
						})
					}
				}
			},
			error:function(){
				console.log('error......')
			}
		}).catch(error=>{
			log('error',error)
		})
	}
	//（预案）联动=>触发预案
	$('.triggerPlan-btn').click(function(){
		var row = $("#alarmtable").bootstrapTable('getSelections')
		if(row.length > 1 || row.length <= 0){
			$.alert('请选择一条预案')
			return;
		}
		$.confirm({
			title:'触发预案',
			content:'预案 : '+row[0].id,
			buttons:{
				确认:async function (){
					doTriggerPlan(row[0]);
				},
				取消:function(){}
			}
		})
	});
	//（预案）联动=>停止预案
	$('.stopPlan-btn').click(function(){
		var row = $("#alarmtable").bootstrapTable('getSelections')
		if(row.length > 1 || row.length <= 0){
			$.alert('请选择一条预案')
			return;
		}
		if(!row[0].activeTime){
			$.alert('预案未开始')
			return;
		}
		$.confirm({
			title:'结束预案',
			content:'预案 : '+row[0].id,
			buttons:{
				确认:async function (){
					doStopPlan(row[0]);
				},
				取消:function(){}
			}
		})
	});
	function doStopPlan(row) {
		$.ajax({
			url:httpProto+'://'+host+'/system-service/api-v1.0/PrePlan/detail/getPrePlanDetailsByPlanId',
			//开发环境
			//url:'http://localhost:8080/api-v1.0/PrePlan/deletePrePlan',
			type: 'get',
			data:{planId:row.id},
			dataType: 'json',
			contentType:'application/json',
			headers:{
				'Authorization':token,
				'Menu_id':'10806',
				'Sysuser_id':sysUserId,
				'Journal_title':encodeURIComponent('${i18n.preplan2}=>${i18n.stop_plan}')
			},
			success:function(res){
				let response = res
				if (response.code === 200) {
					response.data.forEach(item => {
						switch (item.linkType) {
							case 1:
								if(item.broadcastId){
									method = 'broadcast_stop'
									let msg = "'id':'"+item.broadcastId+"'";
									send(msg)
								}
								break
							case 6:
								if(item.broadcastId){
									updateNoticeStatus(item.broadcastId);
								}
								break
						}
					});
				}
			},
			error:function(){
				console.log('error......')
			}
		}).catch(error=>{
			log('error',error)
		})
		//添加操作日志
		$.ajax({
			url:httpProto+'://'+host+'/system-service/api-v1.0/PrePlan/addPrePlanStatusLog',
			//开发环境
			//url:'http://localhost:8080/api-v1.0/PrePlan/deletePrePlan',
			type: 'post',
			data:JSON.stringify({status:'0',planId:row.id}),
			dataType: 'json',
			contentType:'application/json',
			headers:{
				'Authorization':token,
				'Menu_id':'10806',
				'Sysuser_id':sysUserId,
				'Journal_title':encodeURIComponent('${i18n.preplan2}=>${i18n.stop_plan}')
			},
			success:function(res){
				let response = res
				if (response.code === 200) {
					loadActionPlanTable();
				}
			},
		}).catch(error=>{log('error',error)})
	}
	//更新通知状态
	function updateNoticeStatus(id){
		$.ajax({
			url:httpProto+'://'+host+'/control/api_v2.2.5/notice/update/updateNoticeStatus.json',
			//开发环境
			//url:'http://localhost:8080/api-v1.0/PrePlan/deletePrePlan',
			type: 'post',
			data:JSON.stringify({planId:id,status:'3'}),
			dataType: 'json',
			contentType:'application/json',
			headers:{
				'Authorization':authForAll,
			},
			error:function(){
				console.log('error......')
			}
		}).catch(error=>{
			log('error',error)
		})
	}

	/**
	 * （预案）添加
	 * 
	 */
	function addActionPlan(param){
		$.ajax({
			url:httpProto+'://'+host+'/system-service/api-v1.0/PrePlan/addPrePlan',
    		//开发环境
    		//url:'http://localhost:8080/api-v1.0/PrePlan/addPrePlan',
			type: 'post',
			data:JSON.stringify(param),
			dataType: 'json',
			contentType:'application/json',
			headers:{
				'Authorization':token,
				'Menu_id':'10802',
      			'Sysuser_id':sysUserId,
      			'Journal_title':encodeURIComponent('${i18n.preplan2}=>${i18n.add}')
			},
			success:function(res){
				let response = res
				if (response.code === 200) {
					loadActionPlanTable();
					$.alert('成功');
				} else {
				  if (response.msg === '预案已存在') {
					$.alert('预案已存在');
				  } else {
					$.alert('添加失败');
				  }
				}
				$('#reserveplan').modal('hide');
			},
			error:function(){
				// console.log('error......')
				$.alert('添加失败');
				$('#reserveplan').modal('hide');
			}
		}).catch(error=>{
			log('error',error)
		})
	}

	//（预案）终端网关选择
	function reserveplanEmployeeId(){
		var alarmType = $('#alarmType').val();
		var ext = $('#employeeId').val();
		if(alarmType == '1' || alarmType == '2'){
			devicesList.forEach(item=>{
				if(item.exten == ext){
					$('#deptName').val(item.deptName);
					$('#deptId').val(item.deptId);
					$('#ext').val(item.exten);
				}
			});
		}else if(alarmType == '3'){
			alarmDevices.forEach(itme=>{
				if(itme.id == ext){
					if(itme.coms.length > 0){
						var html='';
						itme.coms.forEach(item2=>{
							html+="<option value='"+item2.acId+"'>"+item2.acName+"</option>";
						})
						$('#alarm-deptName').html(`<option style='display: none;'>请选择端口</option>${html}`);
					}
					return;
				}
			});
		}

	}

	//（预案）编辑根据id查询
	function getActionPlanById(id){
		var param={'id':id};
		$.ajax({
			url:httpProto+'://'+host+'/system-service/api-v1.0/PrePlan/getPrePlanById',
    		//开发环境
    		//url:'http://localhost:8080/api-v1.0/PrePlan/getPrePlanById',
			type: 'get',
			data:param,
			dataType: 'json',
			contentType:'application/json',
			headers:{
				'Authorization':token
			},
			success:function(res){
          		if (res.code === 200) {
          		    var actionPlan=res.data[0];
					  $('#alarmType').val(actionPlan.alarmType+'');
					  changeAlarmType();
					  $('#planId').val(actionPlan.id);
					  $('#isActive').val(actionPlan.isActive+'');
					  if(actionPlan.alarmType == 1 || actionPlan.alarmType == 2){
						$('#employeeId').val(actionPlan.ext+'');
						$('#ext').val(actionPlan.ext);
						$('#deptId').val(actionPlan.deptId);
						devicesList.forEach(item=>{
							if(item.exten == actionPlan.ext){
								$('#deptName').val(item.deptName);
							}
						});
						
					  }else if(actionPlan.alarmType == 4 || actionPlan.alarmType == 5){
						$('#camera').val(actionPlan.employeeId+'');
					  }else if(actionPlan.alarmType == 3){
						$('#employeeId').val(actionPlan.employeeId+'');
						reserveplanEmployeeId();
						$('#alarm-deptName option:nth-child(2)').prop("selected", 'selected')
					  }
					
          		}
			},
			error:function(){
				console.log('error......')
			}
		}).catch(error=>{
			log('error',error)
		})
	}
	
	function getDeviceListByUser(){
		var param={'deptId':'','isAdmin':isAdmin,'userDeptId':deptId};
		$.ajax({
			url:httpProto+'://'+host+'/control/api-v2.2.3/20211012/getDeviceListByUser.json',
    		//开发环境
    		//url:'http://localhost:8080/control/api-v2.2.3/20211012/getDeviceListByUser.json',
			type: 'post',
			data:JSON.stringify(param),
			dataType: 'json',
			contentType:'application/json',
			headers:{
				'Authorization':token
			},
			success:function(res){
          		if (res.code === 200) {
          		  	devicesList = res.data
					employeeAndAlarm(1);
          		}
			},
			error:function(){
				console.log('error......')
			}
		}).catch(error=>{
			log('error',error)
		})

	}

	//（预案）1：终端	0：网关
	function employeeAndAlarm(type){
		var html='';
		if(type == 1){
			devicesList.forEach(itme=>{
				html+='<option value="'+itme.exten+'">'+itme.employeeName+'</option>'
			});
		}else{
			alarmDevices.forEach(itme=>{
				html+='<option value="'+itme.id+'">'+itme.name+'</option>'
			});
		}
		
        $('#employeeId').html(`<option style='display: none;'>请选择终端</option>${html}`);
	}

	//（预案） 查询网关
	function queryAlarmDevices(){
		$.ajax({
			url:httpProto+'://'+host+'/system-service/api-v1.0/PrePlan/getAlarmDevices',
    		//开发环境
    		//url:'http://localhost:8080/api-v1.0/PrePlan/getAlarmDevices',
			type: 'get',
			contentType:'application/json',
			headers:{
				'Authorization':token
			},
			success:function(res){
          		if (res.code === 200) {
					alarmDevices = res.data;
          		}
			},
			error:function(){
				console.log('error......')
			}
		}).catch(error=>{
			log('error',error)
		})
	}

	//（预案） 查询摄像头
	function queryAllCamera(){
		$.ajax({
			url:httpProto+'://'+host+'/video-service/api-v1.0/Camera/queryAllCamera',
    		//开发环境
    		//url:'http://localhost:8080/api-v1.0/Camera/queryAllCamera',
			type: 'get',
			contentType:'application/json',
			headers:{
				'Authorization':token
			},
			success:function(res){
          		if (res.code === 200) {
					planAllCamera = res.data;
					allCameraByMotion(1);
				}
			},
			error:function(){
				console.log('error......')
			}
		}).catch(error=>{
			log('error',error)
		})
	}

	//（预案） 获取摄像头数据 1：移动侦测	0：安全帽报警
	function allCameraByMotion(motion){
		var html='';
		var html2='';
		planAllCamera.forEach(itme=>{
			if(itme.motionAlarm == 1){
				html+='<option value="'+itme.id+'">'+itme.deviceNo+'</option>'
			}
			if(itme.motionHelmet == 1){
				html2+='<option value="'+itme.id+'">'+itme.deviceNo+'</option>'
			}
		});
		$('#camera').html(`<option style='display: none;'>请选择摄像头</option>${motion==1?html:html2}`);
	}

	//（预案） table数据查询
	function getAllActionPlan(request){
		$.ajax({
			url:httpProto+'://'+host+'/system-service/api_v2.2.5/prePlan/query/queryAll.json',
    		//开发环境
    		// url:'http://localhost:8080/api-v1.0/PrePlan/getPrePlanList',
			type: 'post',
			data:JSON.stringify(request.data),
			dataType: 'json',
			contentType:'application/json',
			headers:{
				'Authorization':token
			},
			success:function(res){
          		if (res.code === 200) {
					let newData = res.data;
					actionPlanList=newData.list
					actionPlanList.forEach(item=>{
						// devicesList.forEach(item2=>{
						// 	if(item.ext == item2.exten){
						// 	  item.deptName=item2.deptName;
						// 	}
						//   });
						  if(item.deptName == undefined){
							  item.deptName='';
						  }
						switch(item.alarmType){
							case 1:
								item.alarmType = '防拆报警';
							   	break;
						   	case 2:
								item.alarmType = '一键报警';
							   	break;
						   	case 3:
								item.alarmType = '网关报警';
								item.ext='';
							   	break;
						   	case 4:
								item.alarmType = '移动报警';
								item.ext='';
								item.deptName='';
								break;
						   	case 5:
								item.alarmType = '安全帽报警';
								item.ext='';
								item.deptName='';
							   	break;
						   	default:
								item.alarmType = '';
							   	break;
		  				}
						
						if(item.alarmType == '防拆报警' || item.alarmType == '一键报警'){
							allDeptList.forEach(item3=>{
								if(item3.id == item.deptId){
									item.deptName=item3.text;
									return;
								}
							});
						}

						if(item.alarmType == '网关报警'){
							alarmDevices.forEach(item4=>{
								if(item4.id == item.employeeId){
									item.deptName=item4.coms[0].acName;
									return;
								}
							});
						}
						
						switch(item.isActive){
							case 0:
								item.isActive = '关闭';
							   	break;
						   	case 1:
								item.isActive = '自动';
							   	break;
						   	case 2:
								item.isActive = '手动';
							   	break;
						   	default:
								item.isActive = '';
							   	break;
		  				}
						
						  item.status=item.activeTime==null?'未开始':'执行中';

					});
					request.success({
						total: newData.totalCount,
						rows: newData.list
					})
          		}
			},
			error:function(){
				console.log('error......')
			}
		}).catch(error=>{
			log('error',error)
		})
	}
	//（预案）  报警类型
	function changeAlarmType(){
		var alarmType = $('#alarmType').val();
		$('#deptName').val('');
		$('#ext').val('');
		$('#isActive').val('0');
		if(alarmType == '1' || alarmType == '2'){

			$('#camera').css('display','none');
			$('[for=camera]').attr('hidden','hidden');
			$('#ext').attr('type','text');
			$('[for=ext]').removeAttr('hidden');
			$('#deptName').attr('type','text');
			$('[for=deptName]').removeAttr('hidden');
			$('#employeeId').css('display','');
			$('[for=employeeId]').removeAttr('hidden');
			$('#alarm-deptName').css('display','none');
			employeeAndAlarm(1);

		}else if(alarmType == '4' || alarmType == '5'){

			$('#camera').css('display','');
			$('[for=camera]').removeAttr('hidden');
			$('#ext').attr('type','hidden');
			$('[for=ext]').attr('hidden','hidden');
			$('#deptName').attr('type','hidden');
			$('[for=deptName]').attr('hidden','hidden');
			$('#employeeId').css('display','none');
			$('[for=employeeId]').attr('hidden','hidden');
			$('#alarm-deptName').css('display','none');
			if(alarmType == '4'){
				allCameraByMotion(1);
			}else{
				allCameraByMotion(0);
			}
		}else{

			$('#camera').css('display','none');
			$('[for=camera]').attr('hidden','hidden');
			$('#ext').attr('type','hidden');
			$('[for=ext]').attr('hidden','hidden');
			$('#deptName').attr('type','hidden');
			$('[for=deptName]').removeAttr('hidden');
			$('#employeeId').css('display','');
			$('[for=employeeId]').removeAttr('hidden');
			$('#alarm-deptName').css('display','');
			employeeAndAlarm(0);

		}
	}
	let planType = "";//标识预案左侧菜单当前位置
	 //（预案） left
	function loadActionPlanTreeTable(){
		var taskList = [{id:'0',name:'全部预案'},
						{id:'1',name:'防拆报警'},
						{id:'2',name:'一键报警'},
						{id:'3',name:'网关报警'},
						{id:'4',name:'移动报警'},
						{id:'5',name:'安全帽报警'},]
		$("#actionplantreetable").bootstrapTable('destroy')
		$("#actionplantreetable").bootstrapTable({
			cache:false,
			data:taskList,
			clickToSelect:true,
			uniqueId:'id',
			showColumns: false,
			scrollbar:true,
			columns:[{
				field:'name',
				formatter:function(value,item,index){

					var html = "<label class='glyphicon glyphicon-flash'></label>"+value;
					return html;
				}
			}],
			onClickCell:function(field,value,row,$element){
				$("#noticeSearch").show();
				$("#alarmSearch").hide();
				$(".tow_nav").html(value)
				$('.bj-btn').attr('hidden','hidden');
				$('.actionplan-btn').removeAttr('hidden');
				$('.actionplanQuery').removeAttr('hidden');
				planType = "";
				if(value == '防拆报警'){
					planType = "1";
				}else if(value == '一键报警'){
					planType = "2";
				}else if(value == '网关报警'){
					planType = "3";
				}else if(value == '移动报警'){
					planType = "4";
				}else if(value == '安全帽报警'){
					planType = "5";
				}
				loadActionPlanTable();
			}
		})
	}

	//报警left
	function loadAlarmTreeTable(){
		var taskList = [{id:'0',name:'未解除警报'},
					{id:'1',name:'已解除警报'}]
		$("#alarmtreetable").bootstrapTable('destroy')
		$("#alarmtreetable").bootstrapTable({
			cache:false,
			data:taskList,
			clickToSelect:true,
			uniqueId:'id',
			showColumns: false,
			scrollbar:true,
			columns:[{
				field:'name',
				formatter:function(value,item,index){

					var html = "<label class='glyphicon glyphicon-flash'></label>"+value;
					return html;
				}
			}],
			onClickCell:function(field,value,row,$element){
				$("#noticeSearch").hide();
				$("#alarmSearch").show();
				$(".tow_nav").html(value)
				$('.actionplanQuery').attr('hidden','hidden');
				if(value=='未解除警报'){
					$('.bj-btn').removeAttr('hidden');
					$('.actionplan-btn').attr('hidden','hidden');
					unsolve();
				}else if(value == '已解除警报'){
					$('.bj-btn').removeAttr('hidden');
					$('.actionplan-btn').attr('hidden','hidden');
					solve()
				}
				
			}
		})
	}

	var queryType=0;
	function solve(){
		queryType = 3;
		loadAlarmTable()
		$(".tow_nav").html('已解除报警')
	}
	function unsolve(){
		queryType = 1;
		loadAlarmTable()
		$(".tow_nav").html('未解除报警')
	}

	function reloadTable(){
		//重新加载表格
		if(queryType ==1){
			unsolve();
		}else if(queryType == 2){
			solve();
		}else if(queryType == 0){
			loadAlarmTable()
		}
	}

	$('.aconfirm').bind('click',alarmConfirm)
	function alarmConfirm(){
		var alarm_data = $("#alarmtable").bootstrapTable('getSelections');
		if(alarm_data.length > 1 || alarm_data.length <=0){
			$.alert('请选择一条报警任务')
			return;
		}
		openAlarmModel(alarm_data[0])
	}

	var alarmId="";
	var alarmData="";
	var profile="";
	var old_level = "";
	function openAlarmModel(data){
		$('#alarmModal').modal('show')
		$('#alarm-source').val(data.deviceNo)
		$('#alarm-name').val(data.deviceName)
		$('#alarm-level option').each(function(){
			var value = $(this).html()
			if(value == data.alarm_level){
				$(this).attr('selected','selected')
			}
		})
		$('#alarm-desc').val(data.remarks)
		alarmId = data.id
		alarmData = data.alarmData
		profile = data.profile
		old_level = data.alarm_level
	}

	$('.btn-alarm-relieve').bind('click',function(){
		var deviceNo = $('#alarm-source').val();
		var desc = $('#alarm-desc').val()
		var level = $('#alarm-level option:selected').val();
		/* if(old_level == ''||old_level == null||old_level == undefined){
			$.alert('报警未确认')
			return false;
		} */
		alarm_recover(alarmId,deviceNo,profile,alarmData)
		//修改报警状态
		let date = new Date();
		var alarm = '{"id":"'+alarmId+'","status":"3","remarks":"'+desc+'","alarm_level":"'+level+'","confirm_date":"'+dateFormat("YYYY-mm-dd HH:MM:SS",date)+'"}'
		editAlarm(alarm,'报警解除成功！')
		reloadTable()
	})

	$('.btn-alarm-sure').bind('click',alarmSure)
	function alarmSure(){
		var desc = $('#alarm-desc').val()
		var level = $('#alarm-level option:selected').val();
		//修改报警状态
		let date = new Date();
		var alarm = '{"id":"'+alarmId+'","status":"2","remarks":"'+desc+'","alarm_level":"'+level+'","confirm_date":"'+dateFormat("YYYY-mm-dd HH:MM:SS",date)+'"}'
		editAlarm(alarm,'报警确认成功！')
		reloadTable()
	}
	function level(str){
		var _level = ''
		switch(str){
			 			 case "一级":
			 				_level = '1';
			 				break;
			 			case "二级":
			 				_level = '2';
			 				break;
			 			case "三级":
			 				_level = '3';
			 				break;
			 			default:
			 				_level = '';
			 				break;
		}
		return _level;
	}
	$('.aclear').bind('click',alarmRelieve)
	function alarmRelieve(){
		var alarm_data = $("#alarmtable").bootstrapTable('getSelections');
		if(alarm_data.length > 1 || alarm_data.length <=0){
			$.alert('请选择一条报警任务')
			return;
		}
		var data = alarm_data[0]
		if(data.alarm_level == ''||data.alarm_level == null||data.alarm_level == undefined){
			$.alert('报警未确认')
			return false;
		}
		//alarm_recover(data.id,data.device_no,data.profile,data.alarm_data)
		//修改报警状态
		let date = new Date();

		var alarm = '{"id":"'+data.id+'","status":"3","remarks":"'+data.remarks+'","alarm_level":"'+level(data.alarm_level)+'","confirm_date":"'+dateFormat("YYYY-mm-dd HH:MM:SS",date)+'"}'
		editAlarm(alarm,'报警解除成功！')
		reloadTable()
	}

	function  alarm(){
	  method = "alarm";
	  send();
	}
	$('.btn-alarm-speak').bind('click',function(){
		var deviceNo = $('#alarm-source').val();
		alarmCall(deviceNo)
	})

	$('.aspeak').bind('click',function(){
		var alarm_data = $("#alarmtable").bootstrapTable('getSelections');
		if(alarm_data.length > 1 || alarm_data.length <=0){
			$.alert('请选择一条报警任务')
			return;
		}
		var data = alarm_data[0]
		alarmCall(data.device_no)
	})
	function alarmCall(phone){
		if(phone!=""){
			exten = phone
			 method = "call";
			 send();
		} else{
			$.alert("分机号无效！")
		}
	}

	function editAlarm(data,callback){
		if(callback==null || callback == ''||callback==undefined){
			callback = '修改成功！';
		}
		$.ajax({
			url:httpProto+'://'+host+'/control/20180628/infs/identifiyAlarm.json',
			data:data,
			dataType:'json',
			type:'post',
			async:false,
			contentType:'application/json',
			success:function(result){
				if(result.statuscode =='000000'){
					$.alert(callback)
				}else if(result.statuscode=='000003'){
					$.alert('发生错误')
				}
			},
			error:function(){
				$.alert('未知错误')
			}
		})
	}
	/* 报警解除 */
	function  alarm_recover(id,ext,profile,portdata){
	 var  port="";
	 if(portdata.indexOf("port=") != -1){
	    var index = portdata.indexOf("port=");
	    port = portdata.substring(index + 5);
	    if(port.indexOf(";")){
	   	   port=port.split(";")[0];
	    }

	 }

	  var msgtxt="'id':'"+id+"','ext':'"+ext+"','profile':'"+profile+"','port':'"+port+"'";

	  method = "alarm_recover";
	  send(msgtxt);
	}

	function  alarm_send(id,ext,alert_type){
	  var msgtxt="'id':'"+id+"','ext':'"+ext+"','alert_type':'"+alert_type+"'";
	  method = "alarm_send";
	  send(msgtxt);
	}


	/* 会议室相关 */
	var confname;//会议室名称
	var displaynum="88888";//会议号码,可在登录命令查看display_num或自己设置不重复号码
	var isrecord="0";//不录音0录音1,可查看登录命令record_switch或自己定义
	var selectedCP = "";//选中会议成员
	var confrenceNo = ""//选中会议室NO
	var inConfNum = 0;
	var conf_status = []//会议室状态 json 数组
	var isName = 0;//  0固定会议室 1 临时会议室
	var current_displaynum = "";//当前会议室号码
	var inConfExtens = []//在会议室的分机

	/* 移除已开会分机 */
	function removeInconfExten(data){
		inConfExtens = arrunique(inConfExtens)
		if(inConfExtens.length > 0){
			for(let i = inConfExtens.length -1; i>=0; i--){
				if(inConfExtens[i] == data){
					inConfExtens.splice(i,1)
				}
			}
		}
		inConfExtens = arrunique(inConfExtens)
	}

	//获取会议
	function getconferencelist(){
	    method = "getconferencelist";
	    send();
	}
	/* 获取固定会议室 */
	function getGDConf(){
		var base = new Base64();
		var uname = localStorage.rh_username
		var Authorization = base.encode(uname+":"+password)
		var data = [];
		$.ajax({
			url:httpProto+'://'+host+'/control/20211012/infs/getConfoList.json',
			data:'{"userId":"'+uname+'"}',
			type:'post',
			async:false,
			contentType:'application/json',
			dataType:'json',
			beforeSend:function(request){
				request.setRequestHeader("Authorization",Authorization)
			},
			success:function(res){
				let result = res.apiResult;
				if(result.code==200){
					data = result.data
				}
			}
		})
		return data;
	}

	//默认选第一个会议室
	function selectOne(){
		if(confrenceNo == "" || confname == ""){
			var data = $('#gdconfrence').bootstrapTable('getData');
			if(data.length > 0){
				var conf = data[0]
				confrenceNo = conf.confno
				confname = conf.conf_name
				current_displaynum = conf.conf_num
			}
		}

		$(".tow_nav").html(confname)
		if(conf_status.length>0){
			for(let i = 0; i < conf_status.length; i++){
				if(conf_status[i].isName == '0'){
					$('#gdconfrence tbody tr').each(function(){
						if($(this).attr('data-uniqueid') == conf_status[i].confname){
							$(this).addClass('confing')
						}
					})
				}
			}

		}

		var conf_statu = getConfStatusDataByConfName(confname)
		if(conf_statu!="" && conf_statu != null){
			if(conf_statu.isName == '1'){
				var extens = conf_statu.extens
				var exs = []
				for(let i = 0; i < extens.length; i++){
					var ex = {'exten':extens[i].split('@')[0],'employee_name':extens[i].split('@')[0]}
					exs.push(ex)
				}
				loadConfrenceExten(exs)
				changeMul(confname)
				isName = 1;
			}else{
				var confs = getDataByConfName(confname)
				//todo 去除重复分机
				var ex = getExtenJson(conf_statu.extens,confs)
				confs = confs.concat(ex)
				loadConfrenceExten(confs)
				changeMul(confname)
				isName = 0;
			}
		}else{
			//未开会议
			var confs = getDataByConfName(confname)
			loadConfrenceExten(confs)
			isName = 0;
		}

	}
	var gd_conf = []//固定会议室集合,避免每加入一个分机获取一次固定会议室集合
	function confLeft(){
		var data = getGDConf()
		data = generConfList(data);
		data = JSON.parse(JSON.stringify(data).replace(/"conf_name":/g,"\"text\":").replace(/"deptName":/g,"\"text\":").replace(/"children":/g,"\"nodes\":"))

		confTable(data,lsData)
	}
	function generConfList(ConfList) {
		let list = [];
		if(confList && confList.length > 0){
			for (let i = 0; i < confList.length; i++) {
				if(list !=='' && list !=='[]' && list !== undefined){
					let confname = list.find(item2=> item2.confname == confList[i].confname );
					if(confname ==='' || confname ==='[]' || confname ===undefined){
						list.push({confname:confList[i].confname,num:0});
					}
				}else{
					list.push({confname:confList[i].confname,num:0});
				}
			}
			for (let j = 0; j < list.length; j++) {
				let count=0;
				for (let l = 0; l < confList.length ; l++) {
					if(list[j].confname == confList[l].confname){
						count++;
					}
				}
				list[j].num=count;
			}
		}
		generConfListArr(ConfList,list);
		return ConfList;
	}
	function generConfListArr(ConfList,list) {
		for (let i = 0; i < ConfList.length; i++) {
			if(ConfList[i].isDept === '1'){    //分区
				ConfList[i].tags=[0];
				generConfListArr(ConfList[i].children,list);
			}else if(ConfList[i].isDept === '0'){
				ConfList[i].icon = 'glyphicon glyphicon-home'
				//会议
				if(list !== '[]' && list !==undefined){
					for (let j = 0; j < list.length; j++) {
						if(list[j].confname === ConfList[i].confno){
							ConfList[i].tags=[list[j].num];
							//console.log(item2.num);
						}
					}
					if(ConfList[i].tags === '' || ConfList[i].tags === undefined){
						ConfList[i].tags=[0];
					}
				}else{
					ConfList[i].tags=[0];
				}
			}
		}
		numberConfing(ConfList)
	}
	function numberConfing(list){
		for (let i = 0; i < list.length; i++) {
			if (list[i].isDept === '1') {
				let num = 0
				if (list[i].children && list[i].children.length > 0) {
					for (let j = 0; j < list[i].children.length; j++) {
						num += list[i].children[j].tags[0]
						numberConfing(list[i])
					}
				}
				list[i].tags = [num];
			}
		}
	}
	/* 获取临时会议室 */
	function getLSData(gd){
		var lsData = []
		if(confList.length >0 && confList.length > gd.length){
			for (var i = 0; i < confList.length; i++) {
				var ac = confList[i]
				for (var i = 0; i < gd.length; i++) {
					var gc = gd[i]
					if(ac.confname!=gc.conf_name){
						var conf = '{"conf_name":"'+ac.confname+'","confno":"'+ac.uuid+'","speak":"'+ac.IsCanSpeak+'"}'
						lsData.push(conf)
					}
				}
			}
		}
		return lsData;
	}
	/* 生成表格 */
	function confTable(gdData,lsData){
		$("#confTree").text("");
		if(gdData.length > 0){
			$("#confTree").css("text-align","left");
			$("#confTree").treeview({
				data : gdData,// 赋值
				showTags:true,
				onNodeSelected: function(event, node) {
					var value = node.text;
					if(!node.conf_num){
						return;
					}
					$(".tow_nav").html(value)
						confrenceNo = node.confno
						confname = value
						current_displaynum = node.conf_num
						var state = getConfStatusDataByConfName(value)
						var data = getDataByConfName(value);
						if(state != null && state != ''){
							//todo 去除重复分机
							var ex = getExtenJson(state.extens,data)
							data = data.concat(ex)
						}
						//data = arrunique(data)
						loadConfrenceExten(data)
						changeMul(confname)
						isName = 0;
						//清除选中分机
						selectedCP = ""
				},
			});
		}else{
			$("#confTree").css("text-align","center");
			$("#confTree").text("没有找到匹配的记录");
		}
		reloadLsConf(lsData)

		var contentHeight = getVisible();
		var toolBarH = $('.fixed-table-toolbar').height();
		var height = (contentHeight - toolBarH)/2;
		var container = $('.fixed-table-container').css({'height':height})
		$('#confTree').css({'height':height-35})

	}

	/* 重新生成临时会议室*/
	function reloadLsConf(lsData){
		$('#lsconfrence').bootstrapTable('destroy')
		$('#lsconfrence').bootstrapTable({
			cache:false,
			data:lsData,
			clickToSelect:true,
			uniqueId:'conf_name',
			height:'4px',
			showColumns: false,
			scrollbar:false,
			onClickCell:function(field,value,row,$element){
				$(".tow_nav").html(value)
				confrenceNo = row.confno
				confname = value
				current_displaynum = displaynum

				var conf_status = getConfStatusDataByConfName(value)
				var extens = conf_status.extens
				var exs = []
				for(let i = 0; i < extens.length; i++){
					var ex = {'exten':extens[i].split('@')[0],'employee_name':extens[i].split('@')[0]}
					exs.push(ex)
				}
				loadConfrenceExten(exs)
				changeMul(confname)
				isName = 1;
				//清除选中分机
				selectedCP = ""
			},
			columns:[{
				field:'conf_name',
				title:'临时会议室',
				formatter:function(value,item,index){

					var html = "<label class='glyphicon glyphicon-triangle-right'></label>"+value;
					return html;

				}
			}],
		})

		var contentHeight = getVisible();
		var toolBarH = $('.fixed-table-toolbar').height();
		var height = (contentHeight - toolBarH)/2;
		var container = $('.fixed-table-container').css({'height':height})

		$('#lsconfrence tbody tr').each(function(){
			if(!$(this).hasClass('no-records-found')){
				$(this).addClass('confing')
			}

		})
	}
	/* 多方会议 */
	function otherConf(extens){
			 var display_num = Math.floor(Math.random () * 900) + 100;
			 var conf_name = username + display_num;

			 is_record = isrecord//录音
			 method = 'mulconference'
			 var msgtxt = "'confname':'"+conf_name+"','displaynum':'"+displaynum+"','isrecord':'"+is_record+"','extens':'"+extens+"'";


			 //添加会议状态 isName 1 临时会议
			 var param = {'confname':conf_name,'confno':'','status':'open','extens':[],'isName':'1','inConfNum':0,'displaynum':display_num,'mul_all':false,'mul_exten':[]}
			 conf_status.push(param)
			 //生成临时会议室
			 var ls = {'conf_name':conf_name,'confno':display_num}
			 lsData.push(ls)
			 reloadLsConf(lsData)
			 $('#lsconfrence .th-inner').html('')
			 //默认选择临时会议室
			 $(".tow_nav").html(conf_name)
			 confrenceNo = display_num
			 confname = conf_name
			 current_displaynum = display_num
			 isName = 1

			 send(msgtxt)
	}
	
	/* 添加正在开会分机对应会议室的标识 */
	function addExtenInStatus(conf_name){
		var state = getConfStatusDataByConfName(conf_name)
		if(state == null || state == '' || state == undefined){
			console.log('会议未开始!')
			return
		}
		//获取会议中的分机
		var extens = state.extens
		for(let i = 0; i < extens.length; i++){
			var selectedCP = extens[i].split('@')[0]
			$('#i'+selectedCP).removeClass('glyphicon-user')
			$('#i'+selectedCP).addClass('glyphicon-earphone')
		}
	}

	/* 根据会议室名称获取分机 */
	function getDataByConfName(confName){
		var data = getConfsData();
		if(data.length <= 0){
			return [];
		}
		var confs = [];
		for (var i = 0; i < data.length; i++) {
			var conf = data[i]
			if(conf.conf_name == confName){
				confs.push(conf)
			}
		}
		return confs;
	}

	/* 获取全部的分机 */
	function getConfsData(){
		var data = [];
		$.ajax({
			url:httpProto+'://'+host+'/control/20190821/infs/getConfoDetailList.json',
			type:'post',
			data:'{}',
			async:false,
			dataType:'json',
			contentType:'application/json',
			success:function (result){
				if(result.statuscode == '000000'){
					data = result.data
					//inConfNum = data.length;
				}
			}
		})

		return data;
	}

	/* 判断是否是临时会议，并添加进会议数据 */
	function islsConf(data){
		var conf_status = getConfStatusDataByConfName(data.confname)
		var exten = data.ExtenInfo.split(',')[0]
		conf_status.extens.push(exten)
		var gdConf = gd_conf
		for(let i = 0; i < gdConf.length; i++){
			if(gdConf[i].confno == data.confname){
				return false
			}
		}
		return true
	}

	/* 判断是否是用户开启会议 */
	function isOpenConf(data){
		//判断是否是固定会议室
		var conf_name = data.confname
		var isConf = false
		var confInfo = ""
		for(let i = 0; i < gd_conf.length; i++){
			if(gd_conf[i].confno == conf_name){
				isConf = true
				confInfo = gd_conf[i]
				break
			}
		}
		//添加一条开始记录
		if(isConf){
			//判断是否已开启
			var state = getConfStatusDataByConfName(conf_name)
			if(state == null || state == ''){
				//获取对应的固定会议室数据
				var param = {'confname':confInfo.conf_name,'confno':confInfo.confno,'status':'open','extens':[],'isName':'0','inConfNum':0,'displaynum':confInfo.conf_num,'mul_all':false,'mul_exten':[]};
				conf_status.push(param)
				//选中会议
				// $('#gdconfrence tbody tr').each(function(){
				// 	if($(this).attr('data-uniqueid') == confInfo.conf_name){
				// 		$(this).addClass('confing')
				// 	}
				// })
			}

		}
	}

	function addOnlineConfExten(jsonStr){
		let conf_no = jsonStr.confname
		let state = getConfStatusDataByConfNo(conf_no)
		if(state == null || state == ''){
			state = getConfStatusDataByConfName(conf_no)
		}
		if(state == null || state == ''){
			return
		}
		state.inConfNum += 1
	}
	/* 获取临时会议室的分机 */
	function getLsExtens(data){
		if(data == null || data == ''){
			return []
		}


		var gdConf = gd_conf // 所有固定会议室

		var lsConfExtens = []
		if(gdConf.length <= 0){//没有固定会议室，全部都是临时会议室
			return lsConfExtens
		}

		var online_confname = []
		var online_confno = []
		var online_conf_exten = []//{conf_name:exten[]}
		var index = []
		//查看每一个加入的会议室
		for(let j = 0; j < data.length; j++){
			//添加进已开会
			inConfExtens.push(data[j].exten)
			for(let i = 0; i < gdConf.length; i++){
				var gd = gdConf[i]
				if(gd.confno == data[j].confname){
					online_confname.push(gd.conf_name)
					online_confno.push(gd.confno)
					index.push(j)
				}
			}
		}

		//todo 修改对应的，现有可能出现不对应
		online_confname = arrunique(online_confname)
		online_confno = arrunique(online_confno)

		for(let i = 0; i < online_confno.length; i++){
			var param = {'confname':online_confno[i],'extens':[],'mute':[]}
			var extens = []
			var mutes = []
			for(let j = 0; j < data.length; j++){
				if(data[j].exten == null || data[j].exten == '' || data[j].exten == undefined || data[j].exten == 'null'){
					continue
				}
				if(online_confno[i] == data[j].confname){
					extens.push(data[j].exten)
					if(data[j].IsCanSpeak == false || data[j].IsCanSpeak == 'false'){
						mutes.push(data[j].exten)
					}
				}
			}
			param.extens = extens
			param.mute = mutes
			online_conf_exten.push(param)
		}

		if(index.length >= 0){
			for(let i = index.length-1; i >= 0; i--){
				data.splice(index[i],1)
			}

			if(data instanceof Array){
				lsConfExtens = data
			}
		}

		for(let i = 0; i < online_confname.length; i++){
			//var conf_exten = getDataByConfName(online_confname[i])

			var all_exten = []
			var mute_exten = []
			if(online_conf_exten.length > 0){
				for(let j = 0; j < online_conf_exten.length; j++){
					if(online_conf_exten[j].confname == online_confno[i]){
						all_exten = online_conf_exten[j].extens
						mute_exten = online_conf_exten[j].mute
					}
				}
				/* if(all_exten.length > 0){
					for(let k = 0; k < conf_exten.length; k++){
						for(let m = all_exten.length - 1; m >=0; m--){
							if(conf_exten[k].exten == all_exten[m]){
								all_exten.splice(m,1)
							}
						}
					}
				} */
			}


			var param = {'confname':online_confname[i],'confno':online_confno[i],'status':'open','extens':all_exten,'isName':'0','inConfNum':all_exten.length,'mul_all':false,'mul_exten':mute_exten};

			conf_status.push(param)

			// $('#gdconfrence tbody tr').each(function(){
			// 	if($(this).attr('data-uniqueid') == online_confname[i]){
			// 		$(this).addClass('confing')
			// 	}
			//
			// })
		}
		//lsConfExtens = uniqueArray(lsConfExtens,exten)
		return lsConfExtens
	}

	var lsData = []//临时会议数据
	//返回数据为 json 数组 {conf_name:'',confno:''}
	function diffConf(data){

		var lsExtens = getLsExtens(data)
		if(lsExtens.length <= 0 || lsExtens == {}){
			return lsExtens
		}

		var lsConfs = []
		var conf = {'conf_name':lsExtens[0].confname,'confrenceNo':lsExtens[0].MemberID}
		lsConfs.push(conf)

		for(let i = 0; i < lsExtens.length; i++){
			var extens = []
			var ex = lsExtens[i]
			let flag = true
			for(let j = 0; j < lsConfs.length; j++){
				if(ex.confname == lsConfs[j].conf_name){
					flag = false
					break
				}
			}
			if(flag){
				var conf1 = {'conf_name':lsExtens[i].confname,'confrenceNo':lsExtens[i].MemberID}
				lsConfs.push(conf1)
			}

			lsData = lsConfs

		}
		for(let i = 0; i < lsConfs.length; i++){
			var extens = []
			var mute_extens = []
			for(let j = 0; j < lsExtens.length; j++){
				if(lsExtens[j].exten == null || lsExtens[j].exten == 'null'){
					continue
				}
				if(lsConfs[i].conf_name == lsExtens[j].confname){
					extens.push(lsExtens[j].exten)
					if(lsExtens[j].IsCanSpeak == 'false'|| lsExtens[j].IsCanSpeak == false){
						mute_extens.push(lsExtens[j].exten)
					}
				}
			}
			var param = {'confname':lsConfs[i].conf_name,'confno':lsConfs[i].confrenceNo,'status':'open','extens':extens,'isName':'1','inConfNum':extens.length,'dispalynum':current_displaynum,'mul_all':false,'mul_exten':mute_extens};
			conf_status.push(param)
		}
		//添加成员及会议
		return lsConfs
	}


	/* 处理分机数据格式 */
	function produceConfExten(data){
		var ex = []
		if(data != null || data != ''){
			var exs = {'exten':data.ExtenInfo.split('@')[0],'employee_name':data.ExtenInfo.split('@')[0]}
			ex.push(exs)
		}
		return ex
	}

	/* 设置分机状态 */
	function setDataStatus(data){
		if(data.length<=0){
			return [];
		}
		if(data.length>0){
			//设置状态
			for (var i = 0; i < statusList.length; i++) {
				var ex = statusList[i]
				for (var j = 0; j < data.length; j++) {
					var _this = data[j]
					if(ex.number == _this.exten){
						_this.status = ex.status
						/* 添加排序字段 */
						if(_this.status == 'Idle' || _this.status == 'Talking' || _this.status == 'Ringing'){
							_this.order_list = -1;
						}else if(_this.status == 'UnKnow'){
							_this.order_list = 0;
						}else if(_this.status == 'OffLine'){
							_this.order_list = 2;
						}else if(_this.status == 'Broading'){
							_this.order_list = -2;
						}else{
							_this.order_list = 3;
						}
					}
				}
			}
			//设置内外线
			for (var i = 0; i < listData.length; i++) {
				var ex = listData[i]
				var fl = 0;
				var e = "";
				if(ex.exten.indexOf("@")!=-1){
					fl = 1;
					e = ex.exten.split("@")[0]
				}else{
					fl = 0;
					e = ex.exten;
				}
				for (var j = 0; j < data.length; j++) {
					var _this = data[j]
					if(e == _this.exten){
						_this.nw = fl
						_this.deptname = ex.deptname

						if(_this.nw == 0){
							_this.order_list = 0;
						}
					}
				}
			}
		}
		/* 数据排序 */
		data.sort(sortId)
		return data;
	}


	//生成成员
	function  loadConfrenceExten(data){
		data = setDataStatus(data)
		var extlength=data.length;
		var extHtml="";
		for(var i=0;i<extlength;i++){
			//判断内线
			var ex = data[i]
			if(ex.nw == 1){
				extHtml +="<div class='panel col-md-1' id=\"hy"+ex.exten+"\" onclick='extenClick(this)'>"
				extHtml+="<div class=\"panel-heading \" ><h6 class=\"panel-title font-weight-normal\" id=\"y"+ex.exten+"\"><i id='i'"+ex.exten+" class = 'glyphicon'></i>离线</h6></div> ";

			}else{//外线
				if(ex.status == null || ex.status == undefined || ex.status == ''){
					ex.status = 'UnKnow'
				}
				extHtml +="<div class='panel col-md-1' id=\"hy"+ex.exten+"\" onclick='extenClick(this)'>"
				extHtml+="<div class=\"panel-heading \" ><h6 class=\"panel-title font-weight-normal\" id=\"y"+ex.exten+"\">未知</h6></div> ";
			}
			var dn = ex.deptname==undefined?'会议':ex.deptname;
			extHtml += "<div class='panel-body'><ul class=\"list-unstyled\"><li>"+dn+"</li><li><i id=\"i"+ex.exten+"\" class='glyphicon glyphicon-user'></i>"+ex.employee_name+"</li><li>"+ex.exten+"</li></ul></div>"
			extHtml += "</div>";
		}
		$("#confrenceindex").html(extHtml);

		//setTimeout(setConfrenceExtenSelected(),3000)
		setTimeout(setConfrenceExtenList(data),3000)
		//改变开会会议室的成员图标
		setTimeout(addExtenInStatus(confname),3000)
		//重载默认不选分机
		selectedCP = ''
		$('.panel').addClass('col-md-1');
	}

	//加入成员 默认加入的成员都是接通进入,隶属于当前会议室,添加一个属于当前会议室的标识
	function  addConfrenceExten(data){
		data = setDataStatus(data)
		var extlength=data.length;
		var extHtml="";
		for(var i=0;i<extlength;i++){
			//判断内线
			var ex = data[i]
			if(ex.nw == 1){
				extHtml +="<div class='panel col-md-1' id=\"hy"+ex.exten+"\" onclick='extenClick(this)'>"
				extHtml+="<div class=\"panel-heading \" ><h6 class=\"panel-title font-weight-normal\" id=\"y"+ex.exten+"\"><i id='i'"+ex.exten+" class = 'glyphicon'></i>离线</h6></div> ";

			}else{//外线
				if(ex.status == null || ex.status == undefined || ex.status == ''){
					ex.status = 'UnKnow'
				}
				extHtml +="<div class='panel col-md-1' id=\"hy"+ex.exten+"\" onclick='extenClick(this)'>"
				extHtml+="<div class=\"panel-heading \" ><h6 class=\"panel-title font-weight-normal\" id=\"y"+ex.exten+"\">未知</h6></div> ";
			}
			var dn = ex.deptname==undefined?'会议':ex.deptname;
			extHtml += "<div class='panel-body'><ul class=\"list-unstyled\"><li>"+dn+"</li><li><i id=\"i"+ex.exten+"\" class='glyphicon glyphicon-earphone'></i>"+ex.employee_name+"</li><li>"+ex.exten+"</li></ul></div>"
			extHtml += "</div>";
		}
		$("#confrenceindex").prepend(extHtml)

		setTimeout(setConfrenceExtenList(data),3000)
		$('.panel').addClass('col-md-1');
	}

	/* 点击事件 */
	function extenClick(_element){
		var phone = $(_element).children(".panel-body").children().children("li").eq(2).html();
		if($(_element).hasClass('selected')){
			$(_element).removeClass('selected')
			selectedCP = "";
		}else{
			if($(_element).children().children().html()!="离线"&&$(_element).children().html()!=undefined){
				$('#confrenceindex .panel').removeClass('selected')
				$(_element).addClass("selected");
				selectedCP = phone;
			}
		}
	}

	/* 设置分机是否可选 */
	function setConfrenceExtenSelected(){
	        $("#confrenceindex .panel").click(function(){
				var phone = $(this).children(".panel-body").children().children("li").eq(2).html();
	            if($(this).hasClass('selected')){
					$(this).removeClass('selected')
					selectedCP = "";
				}else{
					if($(this).children().children().html()!="离线"&&$(this).children().html()!=undefined){
						$('#confrenceindex .panel').removeClass('selected')
						$(this).addClass("selected");
						selectedCP = phone;
					}
				}
	        });
	}

	//设置分机状态
	function setConfrenceExtenList(extens){

		var extlength=extens.length;
		for(var i=0;i<extlength;i++){
			$("#hy"+extens[i].exten+"").addClass(getStateClass(extens[i].status));
			$("#y"+extens[i].exten+"").html(getState(extens[i].status));
		}
		$("#confrenceindex .paneltitle").each(function(){
			if($(this).html()=="未知"){
				$(this).addClass("panel-warning")
			}
		})


	}
	
	var refData = [];
	var confExData = [];
	/* 获取选中分机 */
	function getSelectConfExten(){
		var data = []
		if(refData.length > 0 && confExData.length > 0){
			for (let i = 0; i < confExData.length; i++) {
				var ce = confExData[i]
				for (let j = 0; j < refData.length; j++) {
					if(ce.exten == refData[j]){
						data.push(ce)
						break;
					}
				}
			}
		}
		//var state = getConfStatusDataByConfName(confname);

		//state.extens = data
		data = arrunique(data)
		return data
	}

	/* 判断进入会议室的是否是固定成员 */
	function isGDExtens(data){
		var exten = data.ExtenInfo.split('@')[0]
		var confs = getDataByConfName(confname)
		//无论是否固定分机都加入数据
		if(confs.length > 0){
			var state = getConfStatusDataByConfName(confname)
			if(state == null || state == ''){
				return
			}
			//无论是否都加入即正在开会的
			state.extens.push(exten)
			for(let i =0; i < confs.length; i++){
				if(confs[i].exten == exten){
					return false
				}
			}
		}
		return true

	}
	function getExtenNumber(expandedKeys, moduleDataList) {
		for (let i = 0; i < moduleDataList.length; i++) {
			if("0" == moduleDataList[i].isDept && !moduleDataList[i].isLinkMan){
				expandedKeys.push(moduleDataList[i].id)
			}
			if("0" == moduleDataList[i].isDept && '1' == moduleDataList[i].isLinkMan){
				expandedKeys.push(moduleDataList[i].value)
			}
			if (moduleDataList[i].children) {
				expandedKeys = this.getExtenNumber(expandedKeys, moduleDataList[i].children)
			}
		}
		return expandedKeys
	}
	function sureAddExten(){
		var data  = transferConf.getTransferData();
		let partIds = [];
		data = getExtenNumber(partIds, data)
		if(data.length<=0){
			return;
		}
		if(noticeType != '-1'){
			let info = ''
			let importArr = []
			let arr = data
			let reg = /^\d+(\.\d+)?$/
			arr.forEach(item => {
				if (!reg.test(item)) {
					flag = false
					info += item
				} else {
					importArr.push(item)
				}
			})
			let _arr = $('#isSelectNum').val().split(',')
			let arrOne = Array.from(new Set([...importArr,..._arr]))
			let str = ''
			arrOne.forEach(item => {
				if (item) {
					str += item + ','
				}
			})
			$('#isSelectNum').val(str.substring(0, str.length - 1))
			return;
		}
		refData = [].concat(data)
		method = 'joinconference'
		var state = getConfStatusDataByConfName(confname);
		if(state == "" || state == null || state == undefined){
			console.log('会议未开始!')
			return
		}
		var param = "";
		if(isName == 0){
			param = state.confno
		}else {
			param = state.confname
		}
		for (let i = 0; i < data.length; i++) {
			var exten = data[i]
			if(exten.indexOf('@')!=-1){
				exten = exten.split('@')[0]
			}
			msgtxt = "'exten':'"+exten+"','confname':'"+param+"','displaynum':'"+current_displaynum+"'"
			send(msgtxt)
		}

	}
	function addExtentAjax(isVideo) {
		$.ajax({
			url:httpProto+"://"+host+"/control/20210927/infs/getDepetAndEmpList.json",
			type:"post",
			data:JSON.stringify({
				deptId:deptId,
				isAdmin:isAdmin,
				labelIsMail:'1'
			}),
			contentType:"application/json",
			dataType:"json",
			async:false,
			success:function(result){
				let response = result.apiResult;
				if (response.code === 200) {
					let fromData = [];
					response.data.forEach(item=>{
						item.pId = '-1';
						item.parentId = '-1';
					});
					let prams = {
						id:'-1',
						pId:'',
						label:'系统分机',
						children:response.data
					}
					fromData.push(prams);

					if (isVideo) {
						//加载摄像头 调度员
						getUserAndCameraList(fromData)
					}else{
						getMailList(fromData);
					}
				}
			}
		})
	}
	function getUserAndCameraList(fromData) {
		let data = {userId}
		$.ajax({
			url:httpProto+'://'+host+'/control/api_v2.2.5/conference/query/getUserAndCamera.json',
			type:'post',
			data:JSON.stringify(data),
			contentType:'application/json',
			dataType:'json',
			headers:{
				'Authorization':token
			},
			success: function (response) {
				if (response.code === 200) {
					let data = JSON.parse(JSON.stringify(response.data))
					let params = {id:'-4',pId:'',label:'调度员',children:data[0].user}
					fromData.push(params)
					params = {id:'-5',pId:'',label:'摄像头',children:data[0].camera}
					fromData.push(params)
				}
				initTransferConf(fromData)
			},
			error:function (error) {


			}
		})
	}
	function getMailList(fromData){
		var base = new Base64();
		var Authorization = base.encode(username+":"+password)
		$.ajax({
			url:httpProto+"://"+host+"/control/api_v1.0/linkMan/tree.json",
			type:"get",
			data:{userId:userId},
			contentType:"application/json",
			dataType:"json",
			headers: {
				'Authorization': Authorization
			},
			async:false,
			success:function(response){
				if (response.code === 200) {
					if(response.data && response.data.length > 0){
						let newData = response.data[0];
						newData.label = "联系人";
						newData.children[0].label = "公有";
						newData.children[1].label = "私有";
						fromData.push(newData);
					}
					initTransferConf(fromData);
				}
			}
		})
	}
	var transferConf = null;
	function initTransferConf(data){
		transferConf = new Transfer()
		//显示搜索框
		transferConf.render({
			elem: '#hytable',
			// 全部数据
			data: data,
			// 已选择数据，默认在右边
			value:[],
			title: ['待选分机', '已选分机'],
			// 是否展示关键词搜索
			showSearch: true,
			// 初始化的所有菜单在 右侧 ,默认 左侧
			isRight:false,
			// 菜单二级全展开
			spread:true,
			uniqueId:'id'
		})
	}
	/* 获取可邀请分机号 */
	function addExtentAjaxOne(){
		var data = []
		$.ajax({
			url:httpProto+'://'+host+'/control/20190821/infs/getConfoExtenList.json',
			data:'{}',
			contentType:'application/json',
			type:'post',
			async:false,
			success:function(result){
				if(result.statuscode == '000000'){
					data = result.data
				}else{
					$.alert('获取数据失败！')
				}
			}
		})

		var temp = {}
		var result = []
		//数组去重
		data.map(function (item,index){
			if(!temp[item.exten]){
				result.push(item)
				temp[item.exten] = true
			}
		})
		//去除已开会分机
		if(inConfExtens.length>0){
			for (let i = 0; i < inConfExtens.length; i++) {
				for (var j = result.length - 1; j >=0 ; j--) {
					var ic = result[j]
					if(ic.exten == inConfExtens[i]){
						result.splice(j,1)
					}
				}
			}
		}
		//data = uniqueArray(data,exten)
		return result
	}

	/* 移除会议静音成员 */
	function removeMuteExten(conf_name,phone){
		var state = getConfStatusDataByConfName(conf_name)
		if(state == null || state == ''){
			return;
		}
		//获取所有静音的分机
		var data = state.mul_exten
		if(data.length <= 0){
			return
		}
		for(let i = data.length - 1; i >=0; i--){
			if(data[i].split('@')[0] == phone){
				state.mul_exten.splice(i,1)
			}
		}
	}
	/* 验证是否静音 */
	function changeMul(confName){
		//固定
		var state = getConfStatusDataByConfName(confName)
		if(state == null || state == ''){
			return;
		}
		//获取所有静音的分机
		var data = state.mul_exten
		//判断是否全部静音
		var all = state.mul_all
		//获取所有的开会的分机
		var extens = state.extens
		for(let i = 0; i < data.length; i++){
			$('#i'+data[i].split('@')[0]).removeClass('glyphicon-earphone')
			$('#i'+data[i].split('@')[0]).addClass('glyphicon-volume-off')
		}
		/* if(isName == 0){

			if(all){
				//获取全部 正在开会的成员对其静音
				for(let i = 0; i < extens.length; i++){
					var se = extens[i]
					$('#i'+se).removeClass('glyphicon-earphone')
					$('#i'+se).addClass('glyphicon-volume-off')
				}
			}else{
				for(let i = 0; i < data.length; i++){
					$('#i'+data[i]).removeClass('glyphicon-earphone')
					$('#i'+data[i]).addClass('glyphicon-volume-off')
				}
			}
		}else {
			if(all){
				//获取全部 正在开会的成员对其静音
				for(let i = 0; i < extens.length; i++){
					var se = extens[i]
					$('#i'+se).removeClass('glyphicon-earphone')
					$('#i'+se).addClass('glyphicon-volume-off')
				}
			}else{
				for(let i = 0; i < data.length; i++){
					$('#i'+data[i]).removeClass('glyphicon-earphone')
					$('#i'+data[i]).addClass('glyphicon-volume-off')
				}
			}
		} */
	}

	/* 移出成员 */
	function moveExten(){
		var state = getConfStatusDataByConfName(confname);
		if(state == "" || state == null || state == undefined){
			console.log('会议未开始!')
			return
		}
		var param = "";
		if(isName == 0){
			param = state.confno
		}else {
			param = state.confname
		}
		if(selectedCP == ''){
			$.alert('请选择成员')
			return false;
		}
		exten =  selectedCP;
		/* var extens = state.extens
		for(let i = extens.length - 1; i>=0; i--){
			if(extens[i] == selectedCP){
				state.extens.splice(i,1)
			}
		} */
		var msgtxt="'confname':'"+param+"'";
		method = "conferencekick"
		send(msgtxt);
	}

	var allMute = false;
	//静音
	function conferencemute(){
		var state = getConfStatusDataByConfName(confname);
		if(state == "" || state == null || state == undefined){
			console.log('会议未开始!')
			return
		}
		var param = "";
		if(isName == 0){
			param = state.confno
		}else {
			param = state.confname
		}
		if(selectedCP == ''){
			$.alert('请选择成员')
			return false;
		}
		 exten =  selectedCP;
		 state.mul_exten.push(exten)

	    var msgtxt="'confname':'"+param+"'";

	    method = "conferencemute";
	    send(msgtxt);
		allMute = false;
	}

	//取消静音
	function conferencecancemute(){
		var state = getConfStatusDataByConfName(confname);
		if(state == "" || state == null || state == undefined){
			console.log('会议未开始!')
			return
		}
		var param = "";
		if(isName == 0){
			param = state.confno
		}else {
			param = state.confname
		}
		if(selectedCP == ''){
			$.alert('请选择成员')
			return false;
		}
		 exten =  selectedCP;
		 var mulEx = state.mul_exten
		 if(mulEx.length >0 ){
			 for(let i = mulEx.length-1; i >=0; i--){
				 if(mulEx[i] == exten){
					 state.mul_exten.splice(i,1)
				 }
			 }
		 }

	    var msgtxt="'confname':'"+param+"'";

	    method = "conferencecancemute";
	    send(msgtxt);
		allMute = false;
	}

	/* 开始会议 */
	function startConference(){
		method = 'conferencestart'
		var msgtxt = "'confname':'"+confname+"','confno':'"+confrenceNo+"'";
		send(msgtxt);
		//记录本条开始的会议
		var exten = []
		var param = {'confname':confname,'confno':confrenceNo,'status':'open','extens':exten,'isName':'0','inConfNum':0,'displaynum':current_displaynum,'mul_exten':[],'mul_all':false};
		conf_status.push(param)
	}

	/* 获取会议数据 */
	function getConfStatusDataByConfName(confName){
		if(conf_status.length<=0){
			return null;
		}
		for(let i = 0; i < conf_status.length; i++){
			if(conf_status[i].confname == confName){
				return conf_status[i]
			}
		}
		return null;
	}

	function getConfStatusDataByConfNo(confno){
		if(conf_status.length<=0){
			return null;
		}
		for(let i = 0; i < conf_status.length; i++){
			if(conf_status[i].confno == confno){
				return conf_status[i]
			}
		}
		return null;
	}


	//静听
	function conferencedeaf(){
		var state = getConfStatusDataByConfName(confname);
		if(state == "" || state == null || state == undefined){
			console.log('会议未开始!')
			return
		}
		var param = "";
		if(isName == 0){
			param = state.confno
		}else {
			param = state.confname
		}
		if(selectedCP == ''){
			$.alert('请选择成员')
			return false;
		}
		 exten =  selectedCP;

	  var msgtxt="'confname':'"+param+"'";

	  method = "conferencedeaf";
	  send(msgtxt);

	}

	//取消静听
	function conferencecancedeaf(){
		var state = getConfStatusDataByConfName(confname);
		if(state == "" || state == null || state == undefined){
			console.log('会议未开始!')
			return
		}
		var param = "";
		if(isName == 0){
			param = state.confno
		}else {
			param = state.confname
		}
		if(selectedCP == ''){
			$.alert('请选择成员')
			return false;
		}
		 exten =  selectedCP;

	  var msgtxt="'confname':'"+param+"'";

	  method = "conferencecancedeaf";
	  send(msgtxt);

	}

	//全部静音
	function conferencemuteall(){
		var state = getConfStatusDataByConfName(confname);
		if(state == "" || state == null || state == undefined){
			console.log('会议未开始!')
			return
		}
		//添加数据
		state.mul_exten = [].concat(state.extens)
		state.mul_all = true
		var param = "";
		if(isName == 0){
			param = state.confno
		}else {
			param = state.confname
		}

	  var msgtxt="'confname':'"+param+"'";

	  method = "conferencemuteall";
	  send(msgtxt);
		allMute = true;
	}

	//取消全部静音
	function conferencecancemuteall(){
		var state = getConfStatusDataByConfName(confname);
		if(state == "" || state == null || state == undefined){
			console.log('会议未开始!')
			return
		}
		state.mul_all = false
		state.mul_exten = []
		var param = "";
		if(isName == 0){
			param = state.confno
		}else {
			param = state.confname
		}

	  var msgtxt="'confname':'"+param+"'";

	  method = "conferencecancemuteall";
	  send(msgtxt);
		allMute = true;
	}
	//关闭会议
	function conferenceclose(){
		var state = getConfStatusDataByConfName(confname);
		if(state == "" || state == null || state == undefined){
			console.log('会议未开始!')
			return
		}
		var param = "";
		if(isName == 0){
			param = state.confno
		}else {
			param = state.confname

			//selectOne()

		}
		state.status = 'close'
		exten =  selectedCP;

	    var msgtxt="'confname':'"+param+"'";

	    method = "conferenceclose";
	    send(msgtxt);
	}

	var close_confname = ""
	var is_notip = false
	function conferencecloseNoTip(conf_name){
		var state = getConfStatusDataByConfName(conf_name);
		if(state == "" || state == null || state == undefined){
			return
		}
		var param = "";
		if(state.isName == '0'){
			param = state.confno
		}else {
			param = state.confname

		}
		close_confname = conf_name
		if(conf_name != confname){
			is_notip = true
		}

		state.status = 'close'
		exten =  selectedCP;

		var msgtxt="'confname':'"+param+"'";

		method = "conferenceclose";
		send(msgtxt);
	}

	//================ 视频模块 ===================== 

	var selectedVideo = null
	var golbalCols = null
	var golbalRows = null
	var selectCol = 0
	var selectRow = 0
	//初始化的每一个视频数据
	var videoElementData = []
	var videoPort = {8030:6,8031:6,8032:6,8033:6,8034:6}
	var videoPorts = {8035:6,8036:6,8037:6,8038:6}

	var allCamera = null
	
	function resetVideoData(moduleDataList){
		for (let i = 0; i < moduleDataList.length; i++) {
			let text = moduleDataList[i].isDept == '0' ? moduleDataList[i].deviceNo : moduleDataList[i].isDept == '1'
				? moduleDataList[i].deptName : moduleDataList[i].employeeName;
			moduleDataList[i].text = text;
			let icon = moduleDataList[i].isDept == '0' ? "glyphicon glyphicon-facetime-video" : moduleDataList[i].isDept == '1'
				? "glyphicon glyphicon-folder-open" : "glyphicon glyphicon-earphone";
			moduleDataList[i].icon = icon;

			if (moduleDataList[i].children) {
				moduleDataList[i].children = resetVideoData(moduleDataList[i].children);
				moduleDataList[i].nodes = moduleDataList[i].children;
			}
		}
		return moduleDataList
	}
	

	function bindEvent(){
		console.trace('------------bindEvent------------')
		//树选择方法
		$('#tree').on('nodeSelected',function(event,data){
			if (data && data.cameraId) {
				selectedVideo = data
				//选中摄像，获取流地址
				//var rtmpJson = getRtmp(data)
				getRtmp(data,(res)=>{
					if (res) {
						if(redborderType){
							playVideo(data,res,null)
							redborderType =false
						}else{
							if(videoOccupyList.length == 0){
								selectRow = 0;
								selectCol = 0;
								playVideo(data,res,null)
							}else{
								for (let i = 0; i < golbalRows; i++) {
									for (let j = 0; j < golbalCols; j++) {
										var temp = videoOccupyList.find(item=> item.selectRow == j && item.selectCol == i);
										if(temp == undefined){
											selectRow = j;
											selectCol = i;
											playVideo(data,res,null)
											return;
										}
									}
								}
								$.alert("未有空闲窗口")
								selectRow = golbalCols-1;
								selectCol = golbalRows-1;
								playVideo(data,res,null)
							}
						}

					}else{
						$.alert("获取视频流失败！")
					}
				})
				//var supportPtz = checkIsSupportPTZ(data)
				// var supportPtz = null
				// if (rtmpJson) {
				// 	playVideo(data,rtmpJson,supportPtz)
				// }
			}else{
				selectedVideo = null
			}
		})
	}


	function getRtmp(data,callback){
		if (!data) {
			//return
			callback(null)
		}
		var result = null
		var param = {}
		param.ip = data.cameraIP
		param.port = data.onvifPort ? data.onvifPort:data.port
		param.user = data.account
		param.password = data.password
		param.rs = 'HIGH'
		param.channel = 1
		if(data.rtsp){
			param.transferType = "1";
			param.rtsp = data.rtsp;
		}
		var ajaxTimeoutTest = $.ajax({
			url: httpProto+'://'+host+'/video-service/api-v1.0/Camera/getRTMP',
			type: 'get',
			data: param,
			dataType: 'json',
			//async:false,
			timeout:10000,
			headers:{
				'Authorization':token
			},
			success:function(data){
				if (data.code === 200) {
					//result = data.data
					callback(data.data)
				}else{
					callback(null)
				}
			},
			error:function(XMLHttpRequest, status, errorThrown){
				if (status == 'timeout') {
					ajaxTimeoutTest.abort()
				}
				callback(null)
			},
			complete:function(XMLHttpRequest,status){
				if (status == 'timeout') {
					ajaxTimeoutTest.abort()
				}
			}
		})
		//return result
	}

	/**
	 * @note 调度通知高级记忆功能
	 *
	 */
	function memberLastRecordForNotice(){
		let type = $("#typeNotice").val();
		let play_type = $("#playType").val();
		$.ajax({
			url: httpProto+'://'+host+'/control/20210204/infs/getNoticeTemplate.json',
			//url: 'http://10.1.20.52/control/20210204/infs/getBroadcastTemplate.json',
			type: 'get',
			async:false,
			data: {type: type,notice_type:play_type},
			dataType:'json',
			success:function(data){
				if (data.statuscode === '000000') {
					let temp = data.data;
					if (temp && JSON.stringify(temp) != '{}' && !isNoticeEdit) {//存在、且是添加操作
						//重试次数
						$("#tryTimes").val(temp.redial_times);
						//振铃时长
						$("#ringTimes").val(temp.max_ring_time);
						//显示号码（需要判断号码仍存在库中）
						set_select_checked("showNumber",temp.pstn_num)
						//并发线数
						$("#currentNum").val(temp.max_concurrent_num);
						//音量值
						$("#volume").slider("setValue",temp.volume)
						//采集按键:
						set_select_checked("recvBtnValue",!temp.dtmf_key ? '*' : temp.dtmf_key)
						//是否采集按键
						$("#recvBtn").prop("checked",!temp.dtmf_key ? false : true);
						//结束通知音
						set_select_checked("endNotice",temp.prompt_tone)
						//是否启用
						$("#noticeEnable").prop("checked",temp.b_enable === '1');
					}
				}
			},
			error:function(){
				console.log('error......')
			}
		}).catch(error=>{
			log('error',error)
		})
	}

	/**
	 * @note 高级记忆功能
	 * 
	*/
	function memberLastRecord(){

		let type = $("#form-data #btype").val();
		let play_type = $("#form-data #broadcasttype").val();

	    let temp = 	getBroadTemplate(type,play_type);

		if (temp && JSON.stringify(temp) != '{}' && !isEdit) {//存在、且是添加操作

			let priority = temp.priority;
			let lasting_time =  temp.lasting_time;
			let volume = temp.volume - 5;//减5操作
			let play_times = temp.play_times;

			//优先级
			$("#form-data #type").val(priority);

			//播放时长
			$("#form-data #broadcasttime").val(lasting_time);

			//音量值（-5）
			$("#form-data #voice").slider("setValue",volume)

			//播放次数
			$("#form-data #broadcasttimes").val(play_times);
			
		}
	}
	/**
	 * @note 获取广播模板
	 * @param type 文字、音乐
	 * @param play_type 即使广播、定时广播、触发广播
	*/
	function getBroadTemplate(type,play_type){

		let return_val ;
		var param = {}
		param.type = type;
		param.playType = play_type;
		$.ajax({

			 url: httpProto+'://'+host+'/control/20210204/infs/getBroadcastTemplate.json',
			//url: 'http://10.1.20.52/control/20210204/infs/getBroadcastTemplate.json',
			type: 'get',
			async:false,
			data:param,
			dataType:'json',
			success:function(data){
				if (data.statuscode === '000000') {
					return_val = data.data;
				}
			},
			error:function(){
				console.log('error......')
			}
		}).catch(error=>{
			log('error',error)
		})
		return return_val
	}

		/**
	 * @note 获取节假日时间模板
	 * @param type = 2
	*/
	function getHoliday(){
		let return_val ;
		var param = {}
		param.type = 2;
		$.ajax({

			url: httpProto+'://'+host+'/control/20210114/infs/getHoliday.json',
			//url: 'http://10.1.20.52/control/20210114/infs/getHoliday.json',
			type: 'get',
			async:false,
			data:param,
			dataType:'json',
			success:function(data){
				if (data.statuscode === '000000') {
					return_val = data.data;
					//增加索引index列10000 + 0
					for (let index = 0; index < return_val.length; index++) {
						const element = return_val[index];
						element.index = 10000+index;
					}
				}
			},
			error:function(){
				console.log('error......')
			}
		}).catch(error=>{
			log('error',error)
		})
		return return_val
	}

	function checkIsSupportPTZ(data){
		if (!data) {
			return
		}
		var param = {}
		var isSupported = false
		param.ip = data.cameraIP
		param.port = data.onvifPort ? data.onvifPort:data.port
		param.user = data.account
		param.password = data.password
		param.rs = 'HIGH'
		param.channel = 1

		$.ajax({
			url: httpProto+'://'+host+'/video-service/api-v1.0/Camera/ptz/isSupport',
			type: 'get',
			async:false,
			data:param,
			headers:{
				'Authorization':token
			},
			dataType:'json',
			success:function(data){
				if (data.code === 200) {
					isSupported = true
				}
			},
			error:function(){
				isSupported = false
			}
		}).catch(error=>{
			log('error',error)
			isSupported = false
		})

		return isSupported
	}


	function initHeight(){
		var height = $('.body').height() - 50
		document.getElementById('videoPanel').style.height = height + 'px'

		var height = $('.body').height() - 60
		$('div[name="flex"]').height(height/1)
		$('div[name="content"]').height(height/1 - 30)
	}

	//初始化面板
	function initPanel(cols,rows){
		golbalCols = cols
		golbalRows = rows
		var colHtml = ''
		$('#videoPanel').html()
		cleanAll()
		for (var i = 0; i < cols; i++) {
			colHtml += "<div name='flex' style='position:relative;' class='videoColor' id='col"+i+"'>"
			var html = ''	
			for (var j = 0; j < rows; j++) {
				html +="<div class='palace' name='flex' oncontextmenu.prevent='stopVideo(this)' onclick='videoClick("+j+","+i+",this)' id='row"+i+j+"'>"
					+"<div id='h"+j+i+"' class='h5videowrapper h5container' onmouseover='show("+j+","+i+")' onmouseout='hide("+j+","+i+")'>" 
					+"<video class='video-js vjs-default-skin h5video' onclick='redborder("+j+","+i+",this)' id='hvideo"+j+i+"' webkit-playsinline playsinline muted>"
					+"</video>"
					+"<div id='videoName"+j+i+"' class='' style='white-space: nowrap;overflow: hidden;text-overflow: ellipsis;text-align: inherit;'></div>"
					+"<div id='rtc"+j+i+"'></div>"
					+"<div class='h5controls' id='controls"+j+i+"' style='display:none;padding:0px'>"
					+"<div style='float:right;padding-right:5px;margin-top:-5px;'>"
					+"<button type='button' title='呼叫' class='vidbuttion pull-right iconfont icon-hujiao' onclick='DoCallExten("+j+","+i+")'></button>"
					+"<button type='button' title='抓拍' class='vidbuttion pull-right iconfont icon-camerafill' onclick='DoSnapshot("+j+","+i+")'></button>"
					+"<button type='button' title='开始录屏' class='vidbuttion pull-right iconfont icon-videofill' onclick='DoManualRecordStart("+j+","+i+")'></button>"
					+"<button type='button' title='停止录屏' class='vidbuttion pull-right iconfont icon-radioboxfill' onclick='DoManualRecordStop("+j+","+i+")'></button>"
					+"<button type='button' style='display:none!important;' title='云台控制' id='ptz"+j+i+"' class='ptz btn vidbuttion pull-right' onclick='PtzControlShow("+j+","+i+")'></button>"
					+"<button type='button' title='全屏' class='vidbuttion pull-right iconfont icon-full' onclick='FullScreen("+j+","+i+")'></button>"
					+"<button type='button' title='停止' class='vidbuttion pull-right iconfont icon-roundclosefill' onclick='CloseVideo("+j+","+i+")'></button>"
					+"</div>"
					+"</div>"
					+"<div class='ptzcontrols' id='pc"+j+i+"' style='display:none;padding:0px'>"
					+"<div class='flex_content'>"
					+"<div class='key_zoom'>"
					+"<div class='zoom'>"
					+"<div class='zoom_add' onmousedown='PtzActionZoomIn(this)' onmouseup='PtzActionStop(this)'></div>"
					+"<div class='zoom_add' onmousedown='PtzActionZoomOut(this)' onmouseup='PtzActionStop(this)'></div>"
					+"</div>"
					+"<div class='key_flex'>"
					+"<div class='key_but'></div>"
					+"<div class='key_but' onmousedown='PtzActionUp(this)' onmouseup='PtzActionStop(this)'></div>"
					+"<div class='key_but'></div>"
					+"<div class='key_but' onmousedown='PtzActionLeft(this)' onmouseup='PtzActionStop(this)'></div>"
					+"<div class='key_but'></div>"
					+"<div class='key_but' onmousedown='PtzActionRight(this)' onmouseup='PtzActionStop(this)'></div>"
					+"<div class='key_but'></div>"
					+"<div class='key_but' onmousedown='PtzActionDown(this)' onmouseup='PtzActionStop(this)'></div>"
					+"<div class='key_but'></div>"
					+"</div>"
					+"</div>"
					+"<div class='Preset'>"
					+"<div class='' style='text-align:center;padding-top:10px'>"
					+"<input id='ps"+j+i+"' name='voice' type='text' data-slider-min='0.1' data-slider-max='1' data-slider-step='0.1' data-slider-value='0.1' class='form-control'/>"
					+"</div>"
					+"</div>"
					+"</div>"
					+"</div>"
					+"</div>"
					+"</div>"
					//记录面板数据
					var vId = 'h'+j+i
					var vJson = {vId:vId,data:{}}
					vJson.data.h5handler = undefined
					vJson.data.ptzShow = false
					vJson.data.ShoutwheatIcon = 'hujiao1'
					vJson.data.ip = ''
					vJson.data.port = ''
					vJson.data.onvifPort = ''
					vJson.data.cId = ''
					vJson.data.videoNameId = 'videoName'+j+i
					vJson.data.rtcId = 'rtc'+j+i
					vJson.data.rtsp = ''
					vJson.data.key = ''
					vJson.data.rKey = ''
					vJson.data.account = ''
					vJson.data.password = ''
					vJson.data.exten = ''
					vJson.data.videoName = ''
					vJson.data.ptzAll = true
					vJson.data.ptzId = 'ptz' + j+i
					vJson.data.psId = 'ps' + j+ i
					vJson.data.pcId = 'pc' + j+i
					vJson.data.employeeId = ''
					vJson.data.cleanBuff = undefined

					videoElementData.push(vJson)
			}
			colHtml += html
			colHtml += "</div>"
		}
		$('#videoPanel').html(colHtml)

		for (var i = 0; i < videoElementData.length; i++) {
			var data = videoElementData[i]
			$('#'+data.data.psId).slider()
		}

		vidoWidth(rows,cols);

	}

	function vidoWidth(rows,cols){
		let Width= document.body.clientWidth;
		setTimeout(function(){
		 if(rows == 3 && cols == 3){
		   for (let i = 0; i < 3; i++) {
			 for (let j = 0; j < 3; j++) {
			   $('#videoName'+j+i).width(Width/4.3);
			 }
		   }
		}else if(rows == 2 && cols == 2){
			 for (let i = 0; i < 2; i++) {
			 for (let j = 0; j < 2; j++) {
			   $('#videoName'+j+i).width(Width/2.6);
			 }
		   }
		}else if(rows == 1 && cols == 1){
		  $('#videoName00').width(Width/1.26);
		}
		},800)
	  }

	function cleanAll(){
		if (videoElementData.length>0) {
			for (var i = 0; i < videoElementData.length; i++) {
				var data = videoElementData[i]
				if (data.data.h5handler) {
					var h5handler = data.data.h5handler
					h5handler.pause()
					h5handler.unload()
					h5handler.detachMediaElement()
					h5handler.destroy()
				}
				if (data.data.cleanBuff) {
					clearInterval(data.data.cleanBuff)
				}
				if (data.data.rKey) {
					stopRecord(data.data.rKey,data.data.ip)
				}
			}
			videoElementData = []
			//还原所有的端口
			videoPort = {8030:6,8031:6,8032:6,8033:6,8034:6}
			videoPorts = {8035:6,8036:6,8037:6,8038:6}
			selectRow = 0
			selectCol = 0
		}
	}

	function CloseVideo(j,i){
		var hId = 'h' + j + i 
		closeVideo(hId)
	}

	function DoCallExten(j,i){
		var hId = 'h'+j+i
		for (var k = 0; k < videoElementData.length; k++) {
			var data = videoElementData[k]
			if (data.vId === hId) {
				var ext = data.data.exten
				var status = getExtenStatus(ext)
				if (ext !== callee && ext !== caller) {
					if (status === 'Idle') {
						exten = ext
				 		method = "call"
				 		send()
					}else if (status === 'Talking' || status === 'Ringing' || status === 'Broading'){
						exten = ext
			    		method = "handup"
			    		send()
					}else{
						alert('分机不在线')
					}
				}else{
					alert('不能呼左右分机')
				}
				break
			}
		}

	}

	function getExtenStatus(exten){
		var status = null
		if(statusList.length>0){
			for (var i = 0; i < statusList.length; i++) {
				var data = statusList[i]
				if (data.number === exten) {
					status = data.status
					break
				}
			}
		}
		return status
	}

	function ptzAction(h5handler,ip,port,account,password,direction,x,y){
		if (!h5handler) {
			return
		}
		var param ={}
		param.ip = ip
		param.user = account
		param.password = password
		param.direction = direction
		param.x = x
		param.y = y
		param.moveType = 'relative'
		param.channel = 1
		param.port = port
	}

	//开始录屏
	function DoManualRecordStart(j,i){
		var hId = 'h' + j + i
		var vJson = null
		for (var k = 0; k < videoElementData.length; k++) {
			var data = videoElementData[k]
			if (data.vId === hId) {
				vJson = data.data
				break
			}
		}
		if (!vJson) {
			return
		}
		var param = {}
		param.rtsp = vJson.rtsp
		param.ip = vJson.ip
		param.cameraId = vJson.cId
		param.employeeId = vJson.employeeId
		param.userName = username
		param.user = vJson.account
		param.password = vJson.password
		param.rs = 'HIGH'
		param.channel = 1
		param.port = vJson.port

		$.ajax({
			url: httpProto+'://'+host+'/video-service/api-v1.0/CameraRecord/videoRecord',
			type: 'post',
			data: JSON.stringify(param),
			dataType: 'json',
			contentType:'application/json',
			headers:{
				'Authorization':token
			},
			success:function(data){
				if (data.code === 200) {
					vJson.rKey = data.data
					alert('开始录屏')
				}else{
					alert('录屏失败')
				}
			}
		})
	}

	function DoManualRecordStop(j,i){
		var hId = 'h' + j + i
		for (var k = 0; k < videoElementData.length; k++) {
			var data = videoElementData[k]
			if (data.vId === hId) {
				var vJson = data.data
				var stop = stopRecord(vJson.rKey,vJson.ip)
				if (stop) {
					vJson.rKey = ''
					alert('停止录屏')
				}
				break
			}
		}
	}

	function stopRecord(rKey,ip){
		var param = {}
		param.key = rKey
		param.ip = ip
		param.userName = username
		var result = true
		$.ajax({
			url: httpProto+'://'+host+'/video-service/api-v1.0/CameraRecord/stopVideoRecord',
			type: 'post',
			data:JSON.stringify(param),
			dataType: 'json',
			contentType: 'application/json',
			async:false,
			headers:{
				'Authorization':token
			},
			success:function(data){
				if (data.code === 200) {
					result = true
				}else{
					result = false
				}
			}
		})
		return result
	}

	//显示云台控制 暂时不做
	function PtzControlShow(j,i){
		var hId = 'h' + j+i
		for (var k = 0; k < videoElementData.length; k++) {
			var data = videoElementData[k]
			if (data.vId === hId) {
				var psId = data.data.psId
				var pcId = data.data.pcId
				var ptzShow = data.data.ptzShow
				if (!ptzShow) {
					$('#'+pcId).css('display','block')
					videoElementData[k].data.ptzShow = true
				}else{
					$('#'+pcId).css('display','none')
					videoElementData[k].data.ptzShow = false
				}
				
			}
		}
	}

	//抓拍
	function DoSnapshot(j,i){
		var hId = 'h'+j+i
		var vJson = null
		for (var k = 0; k < videoElementData.length; k++) {
			var data = videoElementData[k]
			if (data.vId === hId) {
				vJson = data.data
				break
			}
		}
		if (vJson) {
			if (!vJson.h5handler) {
				return
			}
			var param = {}
			param.rtsp = vJson.rtsp
			param.ip = vJson.ip
			param.employeeId = vJson.employeeId
			param.userName = username
			param.cameraId = vJson.cId
			param.user = vJson.account
			param.password = vJson.password
			param.port = vJson.onvifPort

			$.ajax({
				url: httpProto+'://'+host+'/video-service/api-v1.0/CameraRecord/imageRecord',
				type: 'post',
				data: JSON.stringify(param),
				dataType: 'json',
				contentType:'application/json',
				headers:{
					'Authorization':token
				},
				success:function(data){
					if (data.code === 200) {
						alert('截图成功！')
					}else{
						alert('截图失败！')
					}
				}
			})
		}
	}


	//播放视频
	function playVideo(baseData,rtmpData,isSupported){
		//选中的视频窗口ID
		var hId = 'h' + selectRow + selectCol
		var videoId = 'hvideo' + selectRow + selectCol
		//先清
		closeVideo(hId)
		var proData = null
		var rtmp = rtmpData.http
		if (videoElementData) {
			for (var i = 0; i < videoElementData.length; i++) {
				var vJson = videoElementData[i]
				if (vJson.vId === hId) {
					proData = vJson.data
					break
				}
			}
		}
		if (proData) {
			var hh = proData.h5handler
			if (hh) {
				hh.pause()
				hh.unload()
				hh.detachMediaElement()
				hh.destroy()
			}

			if (!isSupported) {
				document.getElementById(proData.ptzId).style.display = 'none'
			}
			var port = null
			if (!proData.port) {
				port = getNoUsePort()
			}else {
				port = proData.port
			}

			var prefix = rtmp.split('//')[0]
			var sufferfix = rtmp.split(':8081')[1]
			rtmp = prefix + '//'+hostNoPort+':8081'+sufferfix

			if (httpProto.indexOf('https')>-1) {
				rtmp = httpProto + '://'+hostNoPort+':8081'+sufferfix
			}

			rtmp = rtmp.replace('8081',port)

			

			var video = document.getElementById(videoId)
			var h5handler = flvjs.createPlayer({
				type: 'flv',
				url: rtmp,
				enableWorker: true,
				enableStashBuffer: false,
				autoCleanupSourceBuffer: true,
				autoCleanupMaxBackwardDuration: 60,
				stashInittialSize: 128,
				isLive: true
			})
			h5handler.attachMediaElement(video)
			h5handler.load()
			h5handler.on('error',(error)=>{
				if (error === flvjs.ErrorTypes.NETWORK_ERROR) {
					log('error','获取流失败！')
				}
			})
			h5handler.play()
			var videoName = baseData.employeeName +'-'+baseData.deviceNo
			if (videoName) {
				var nameId = proData.videoNameId
				$('#'+nameId).html(videoName)
				$('#'+nameId).attr('title',videoName)
				$('#'+nameId).addClass('videoname')
				videoOccupyList.push({'selectRow':selectRow,'selectCol':selectCol});
			}

			//存储数据
			proData.h5handler = h5handler
			proData.port = port
			proData.onvifPort = baseData.onvifPort ? baseData.onvifPort:baseData.port
			proData.ip = baseData.cameraIP
			proData.cId = baseData.cameraId
			proData.videoName = videoName
			proData.rtsp = rtmpData.rtsp
			proData.key = rtmpData.key
			proData.exten = baseData.exten
			proData.employeeId = baseData.employeeId
			proData.account = baseData.account
			proData.password = baseData.password
			proData.cleanBuff = setInterval(jumpToEndBuffer(h5handler),3*10*1000)
			video.addEventListener('pause',()=>{
				if (h5handler) {
					h5handler.play()
				}
			})
		}

	}

	//关闭视频
	function closeVideo(videoId){
		var vData = null
		if (videoElementData.length>0) {
			for (var i = 0; i < videoElementData.length; i++) {
				var data = videoElementData[i]
				if (data.vId === videoId) {
					vData = data.data
					break
				}
			}
		}
		if (vData) {
			var h5handler = vData.h5handler
			if (h5handler) {
				h5handler.pause()
				h5handler.unload()
				h5handler.detachMediaElement()
				h5handler.destroy()
			}
			if(vData.rKey){
				stopRecord(vData.rKey,vData.ip)
				vData.rKey = ''
			}
			if (vData.cleanBuff) {
				clearInterval(vData.cleanBuff)
			}
			var vId = vData.videoNameId
			$('#'+vId).html('')
			$('#'+vId).removeClass('videoname')
			$('#'+vData.rtcId).removeClass('rtc_new')

			//document.getElementById(vData.ptzId).style.display = 'block'

			returnPort(vData.port)
			vData.h5handler = undefined
			vData.ip = ''
			vData.port = ''
			vData.cId = ''
			vData.rtsp = ''
			vData.key = ''
			vData.rKey = ''
			vData.account = ''
			vData.password = ''
			vData.exten = ''
			vData.videoName = ''
			vData.employeeId = ''
			vData.onvifPort = ''
			vData.cleanBuff = undefined		

			var index = videoOccupyList.findIndex(item=> 'h'+item.selectRow+item.selectCol == videoId);
			if(index != -1){
				videoOccupyList.splice(index,1);
			}

		}
	}

	function jumpToEndBuffer(h5handler){
		if (h5handler) {
			var buffered = h5handler.buffered
			if (buffered.length>0) {
				var end = buffered.end(0)
				if (end - h5handler.currentTime > 0.15) {
					h5handler.currentTime = end - 0.1
				}
			}
		}
	}

	function getNoUsePort(){
		var port = null
		if (httpProto.indexOf('s')>-1) {
			for (var key in videoPorts) {
			if(videoPorts[key] > 0){
				port = key
				videoPorts[key] = videoPorts[key] - 1
				break
			}
		}
		}else{
			for (var key in videoPort) {
			if(videoPort[key] > 0){
				port = key
				videoPort[key] = videoPort[key] - 1
				break
			}
		}
		}
		return port
	}

	function returnPort(port){
		if (port) {
			if (httpProto.indexOf('s')>-1) {
				videoPorts[port] = videoPorts[port] + 1
			}else{
				videoPort[port] = videoPort[port] + 1
			}
			
		}
	}

	function FullScreen(j,i){
		let elem = document.getElementById('h'+j+i)
		if (document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled ||document.msFullscreenEnabled) {
			if (document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement) {
				if (document.exitFullscreen) {
					document.exitFullscreen()
				}else if (document.webkitExitFullscreen) {
					document.webkitExitFullscreen()
				}else if (document.mozCancelFullScreen) {
					document.mozCancelFullScreen()
				}else if (document.msExitFullscreen) {
					document.msExitFullscreen()
				}

				updateVideoUIExitFullScreen()
			}else {
				if (elem.requestFullscreen) {
					elem.requestFullscreen()
				}else if (elem.webkitRequestFullscreen) {
					elem.webkitRequestFullscreen()
				}else if (elem.mozRequestFullScreen) {
					elem.mozRequestFullScreen()
				}else if (elem.msRequestFullscreen) {
					elem.msRequestFullscreen()
				}
			}
		}
	}

	function updateVideoUIExitFullScreen(){
		if (!document.fullscreenElement && !document.webkitIsFullScreen && !document.mozFullScreen && !document.msFullscreenElement) {
			$('div[name="flex"]').height(screen/1)
		}
	}

	function show(j,i){
		$('.h5controls').css('display','none')
		$('#controls'+j+i).css('display','block')
	}

	function hide(j,i){
		$('#controls'+j+i).css('display','none')
	}

	function videoClick(j,i,event){
		var parent = $('#row'+i+j)
		if(parent.parent().hasClass('videoClickColor')){
			parent.parent().removeClass('videoClickColor')
		}else{
			$('#videoPanel div[class*="videoClickColor"]').removeClass('videoClickColor')
			$('#videoPanel>div').eq(j-1).children('div').eq(i-1).addClass('videoClickColor')
		}
	}

	//改变面板
	function changePanel(event){
		var data = event.getAttribute('data-row')
		var rows = 1
		if (data === '1|1') {
			initPanel(1,1)
			rows = 1
		}else if (data === '2|2') {
			initPanel(2,2)
			rows = 2
		}else if (data === '3|3') {
			initPanel(3,3)
			rows = 3
		}
		videoOccupyList = [];
		var height = $('.body').height() - 60
		$('div[name="flex"]').height(height/rows)
	}


	//全屏
	function panelFullScreen(event){
		var elem = document.getElementById('videoPanel')
		if (document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled ||document.msFullscreenEnabled) {
			if (document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement) {
				if (document.exitFullscreen) {
					document.exitFullscreen()
				}else if (document.webkitExitFullscreen) {
					document.webkitExitFullscreen()
				}else if (document.mozCancelFullScreen) {
					document.mozCancelFullScreen()
				}else if (document.msExitFullscreen) {
					document.msExitFullscreen()
				}

				updateUIExitFullScreen()
			}else {
				if (elem.requestFullscreen) {
					elem.requestFullscreen()
				}else if (elem.webkitRequestFullscreen) {
					elem.webkitRequestFullscreen()
				}else if (elem.mozRequestFullScreen) {
					elem.mozRequestFullScreen()
				}else if (elem.msRequestFullscreen) {
					elem.msRequestFullscreen()
				}

				updateUIEnterFullScreen()
				if (document.addEventListener) {
					document.addEventListener('webkitfullscreenchange',updateUIExitFullScreen,false)
					document.addEventListener('mozfullscreenchange',updateUIExitFullScreen,false)
					document.addEventListener('fullscreenchange',updateUIExitFullScreen,false)
					document.addEventListener('MSFullscreenChange',updateUIExitFullScreen,false)
				}
			}
		}
	}

	function updateUIExitFullScreen(){
		if (!document.fullscreenElement && !document.webkitIsFullScreen && !document.mozFullScreen && !document.msFullscreenElement) {
			var height = $('.body').height() - 60
			$('div[name="flex"]').height(height / golbalRows)
		}
	}

	function updateUIEnterFullScreen(){
		$('div[name="flex"]').height(screen.height/golbalRows)
	}

	
	function redborder(j,i,event){
		var cors = j * i
		var hId = 'h'+j+i
		var h5handler = null
		var ptzAll = null
		for (var k = 0; k < videoElementData.length; k++) {
			var data = videoElementData[k]
			if (data.vId === hId) {
				h5handler = data.data.h5handler
				ptzAll = data.data.ptzAll
			}
		}
		if (h5handler===undefined) {
			ptzAll = true
		}
		/*if (ptzAll) {
			if (cors>9) {
				document.getElementById('ptz'+j+i).style.display = 'none'
			}
			if (cors<=9) {
				document.getElementById('ptz'+j+i).style.display = 'block'
			}
		}*/
		$('video').removeClass('h5videoh')
		$('#hvideo'+j+i).addClass('h5videoh')
		selectCol = i
		selectRow = j
		redborderType = true;
	}

	function checkSupportFlv(){
		if (!flvjs.isSupported()) {
			alert('浏览器不支持flv')
		}
	}



	// 显示抓拍记录
	$('.video-image').bind('click',function(){
		$('#picModal').modal('show')
		//加载
		generatorPicTable()
	})

	function loadPic(request){
		$.ajax({
			url: httpProto+'://'+host+'/video-service/api-v1.0/CameraRecord/queryImageRecordForPage',
			type: 'post',
			data: JSON.stringify(request.data),
			contentType: 'application/json; charset=utf-8',
			dataType: 'json',
			headers:{
				'Authorization':token
			},
			success:function(data){
				if (data.code === 200) {
					let newData = data.data;
					if (newData.list && newData.list.length>0) {
						newData.list.sort(function(v1,v2){
							return v2.id - v1.id
						})
					}
					request.success({
						total: newData.totalCount,
						rows: newData.list
					})
				}else{
					alert('加载数据出错')
				}
			}
		})
	}

	function generatorPicTable(){
		$('#picTable').bootstrapTable('destroy');
		 $('#picTable').bootstrapTable({
			 cache:false,
			 data:'',
			 clickToSelect:true,
			 uniqueId:'id',
			 showColumns:false,
			 scrollbar:true,
			 search:false,
			 height:'500px',
			 autoHeight: true,
			 ajax:loadPic,
			 queryParams : function (params) {
				 //这里的是搜索条件
				 let temp = {
					 imageName:$("#picImageName").val(),
					 employeeName:$("#picEmployeeName").val(),
					 cameraName:$("#picCameraName").val(),
					 createDateBegin:"",//创建时间开始
					 createDateEnd:"",//创建时间结束
					 userId:userId,
					 currPage:(params.offset / params.limit) + 1,
					 pageLimit:params.limit,
					 properties:params.sort,
					 direction:params.order,
				 };
				 return temp;
			 },
			 pagination: true,
			 pageNumber:1,
			 sidePagination:'server',
			 pageSize:10,
			 pageList:[10, 20, 50, 100],
			 columns:[
			 {
			 	field:'id',
			 	title:'id',
			 	hidden:true,
			 	align:'center',
			 	valign: 'middle',
			 },{
			 	field:'imageName',
			 	title:'图片名称',
			 	align:'center',
			 	valign: 'middle',
			 },{
			 	field:'employeeName',
			 	title:'终端名称',
			 	align:'center',
			 	valign: 'middle',
			 },{
			 	field:'cameraName',
			 	title:'摄像头标识名',
			 	align:'center',
			 	valign: 'middle',
			 },{
			 	field:'createDate',
			 	title:'创建时间',
			 	align:'center',
			 	valign: 'middle',
			 },{
			 	field:'remarks',
			 	title:'操作',
			 	align:'center',
			 	width:120,
			 	valign: 'middle',
			 	formatter: function(value,row,index){
			 		var e = "<a href='javascript:;' onclick='viewPic(\""+row.imageFileName+"\")'>查看</a> "
			 		var d = "<a href='javascript:;' onclick='downloadPic(\""+row.imageFileName+"\")'>下载</a>"
			 		if(row.imageFileName){
			 			return e + d
			 		}else{
			 			return ''
			 		}
			 	}
			 }]

			})
	}

	function viewPic(path){
		if (!path) {
			return
		}
		$('#pic-record').html('')
		var rpath = path.split('/webapps/')[1]
		var apath = httpProto+'://'+host+"/"+rpath
		var img = '<img style="max-width:800px;max-height:650px;" src='+apath+'></img>'
		$('#pic-record').html(img)
		$('#viewPicModal').modal('show')
	}

	function downloadPic(path){
		if (!path) {
			return
		}
		var apath = httpProto+'://'+host+"/video-service/api-v1.0/CameraRecord/downloadFile?path="+path+"&token="+token
		const a = document.createElement('a')
		a.href = apath
		a.click()
	}

	//显示录像记录
	$('.video-record').bind('click',function(){
		$('#videoRecordModal').modal('show')
		generatorVideoTable()
	})

	function loadVideo(request){
		var param = {}
		param.employeeId = -1
		param.cameraId = -1
		$.ajax({
			url: httpProto+'://'+host+'/video-service/api-v1.0/CameraRecord/queryVideoRecordForPage',
			type: 'post',
			data: JSON.stringify(request.data),
			contentType: 'application/json; charset=utf-8',
			dataType: 'json',
			headers:{
				'Authorization':token
			},
			success:function(data){
				if (data.code === 200) {
					let newData = data.data;
					if (newData.list && newData.list.length>0) {
						newData.list.sort(function(v1,v2){
							return v2.id - v1.id
						})
					}
					request.success({
						total: newData.totalCount,
						rows: newData.list
					})
				}
			}
		})
	}



	function generatorVideoTable(videoData){
		$('#videoTable').bootstrapTable('destroy');
		 $('#videoTable').bootstrapTable({
			 cache:false,
			 data:videoData,
			 clickToSelect:true,
			 uniqueId:'id',
			 showColumns:false,
			 scrollbar:true,
			 search:false,
			 height:'500px',
			 autoHeight: true,
			 ajax:loadVideo,
			 queryParams : function (params) {
				 //这里的是搜索条件
				 let temp = {
					 videoName:$("#videoImageName").val(),
					 employeeName:$("#videoEmployeeName").val(),
					 cameraName:$("#videoCameraName").val(),
					 createDateBegin:"",//创建时间开始
					 createDateEnd:"",//创建时间结束
					 userId:userId,
					 currPage:(params.offset / params.limit) + 1,
					 pageLimit:params.limit,
				 };
				 return temp;
			 },
			 pagination: true,
			 pageNumber:1,
			 sidePagination:'server',
			 pageSize:10,
			 pageList:[10, 20, 50, 100],
			 columns:[
			 {
			 	field:'id',
			 	title:'id',
			 	hidden:true,
			 	align:'center',
			 	valign: 'middle',
			 },{
			 	field:'videoName',
			 	title:'图片名称',
			 	align:'center',
			 	valign: 'middle',
			 },{
			 	field:'employeeName',
			 	title:'终端名称',
			 	align:'center',
			 	valign: 'middle',
			 },{
			 	field:'cameraName',
			 	title:'摄像头标识名',
			 	align:'center',
			 	valign: 'middle',
			 },{
			 	field:'createDate',
			 	title:'创建时间',
			 	align:'center',
			 	valign: 'middle',
			 },{
			 	field:'remarks',
			 	title:'操作',
			 	align:'center',
			 	width:120,
			 	valign: 'middle',
			 	formatter: function(value,row,index){
			 		var e = "<a href='javascript:;' onclick='viewVideo(\""+row.videoFileName+"\")'>查看</a> "
			 		var d = "<a href='javascript:;' onclick='downloadVideo(\""+row.videoFileName+"\")'>下载</a>"
			 		if(row.videoFileName){
			 			return e + d
			 		}else{
			 			return ''
			 		}
			 	}
			 }]

			})
	}

	var viewVideoId = undefined
	function viewVideo(path){
		if (!path) {
			return
		}
		closeViewVideo()
		$('#viewVideoModal').modal('show')
		var rpath = path.split('/webapps/')[1]
		var apth = httpProto+'://'+host+"/"+rpath
		var vIE = document.getElementById('vvId')
		viewVideoId = flvjs.createPlayer({
			type:'flv',
			playbackRates: [0.7,1.0,1.5,2.0],
			url: apth
		})
		viewVideoId.attachMediaElement(vIE)
		viewVideoId.load()
		viewVideoId.play()

	}


	function downloadVideo(path){
		if (!path) {
			return
		}
		var path = httpProto+'://'+host+'/video-service/api-v1.0/CameraRecord/downloadFile?path='+path
		const a = document.createElement('a')
		a.href = path
		a.click()
	}

	function closeViewVideo(){
		if (viewVideoId) {
			viewVideoId.pause()
			viewVideoId.unload()
			viewVideoId.detachMediaElement()
			viewVideoId.destroy()
			viewVideoId = undefined
		}
	}

	function setAllDeptList(data){
		data.forEach(item=>{
			allDeptList.push(item);
			if(item.id != '-1' && item.nodes.length > 0){
				setAllDeptList(item.nodes);
			}
		});
	}

	function setMapExten(exten){
		for (let i = 0; i < exten.length; i++) {
			var number = exten[i].number;
			var status = exten[i].status;
			var network = exten[i].network;
			var img = "";
			if($(".MarkerState_"+number).length >0){
				if(status == "Idle"){
					img="dist/img/station/online.png";
					stateName="在线";
				}else if(status == "OffLine"){
					img="dist/img/station/offline.png";
					stateName="离线";
				}else if(status == "Ringing"){
					img="dist/img/station/ring.png";
					stateName="振铃";
				}else if(status == "UnKnow"){
					img="dist/img/station/unknow.png";
					stateName="未知";
				}else if(status == "Talking"){
					img="dist/img/station/talking.png";
					stateName="通话中";
				}else if(status == "alarm"){
					img="dist/img/station/alarm.png";
					stateName="报警";
				}else if(status == "Broading"){
					img="dist/img/station/broading.svg";
					stateName="广播";
				}
				var title =$(".MarkerState_"+number).attr("title");
				var a =title.substring(0,title.indexOf("状态 : "));
				var b =title.substring(title.indexOf("所属分区"),title.indexOf("终端IP"));
				var c =`${a}状态 : ${stateName}
${b}`;
				var d=`${c}终端IP : ${network==""?"未知":network}`;
				$(".MarkerState_"+number).attr("title",d);
				$(".MarkerState_"+number+" img").attr("src",img);
				$(".MarkerState_"+number).children("div:last").html(stateName);
			}
			
			
		}
		
	}


	function getFormatDate(fmt,date){
		let ret;
		let opt = {
		  "Y+": date.getFullYear().toString(),        // 年
		  "m+": (date.getMonth() + 1).toString(),     // 月
		  "d+": date.getDate().toString(),            // 日
		  "H+": date.getHours().toString(),           // 时
		  "M+": date.getMinutes().toString(),         // 分
		  "S+": date.getSeconds().toString()          // 秒
		  // 有其他格式化字符需求可以继续添加，必须转化成字符串
		}
		for (let k in opt) {
		  ret = new RegExp("(" + k + ")").exec(fmt);
		  if (ret) {
			fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
		  }
		}
		return fmt;
	}


	/* method */
	function Base64() {

	    // private property
	    _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

	    // public method for encoding
	    this.encode = function (input) {
	        var output = "";
	        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
	        var i = 0;
	        input = _utf8_encode(input);
	        while (i < input.length) {
	            chr1 = input.charCodeAt(i++);
	            chr2 = input.charCodeAt(i++);
	            chr3 = input.charCodeAt(i++);
	            enc1 = chr1 >> 2;
	            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
	            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
	            enc4 = chr3 & 63;
	            if (isNaN(chr2)) {
	                enc3 = enc4 = 64;
	            } else if (isNaN(chr3)) {
	                enc4 = 64;
	            }
	            output = output +
	                _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
	                _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
	        }
	        return output;
	    }

	    // public method for decoding
	    this.decode = function (input) {
	        var output = "";
	        var chr1, chr2, chr3;
	        var enc1, enc2, enc3, enc4;
	        var i = 0;
	        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
	        while (i < input.length) {
	            enc1 = _keyStr.indexOf(input.charAt(i++));
	            enc2 = _keyStr.indexOf(input.charAt(i++));
	            enc3 = _keyStr.indexOf(input.charAt(i++));
	            enc4 = _keyStr.indexOf(input.charAt(i++));
	            chr1 = (enc1 << 2) | (enc2 >> 4);
	            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
	            chr3 = ((enc3 & 3) << 6) | enc4;
	            output = output + String.fromCharCode(chr1);
	            if (enc3 != 64) {
	                output = output + String.fromCharCode(chr2);
	            }
	            if (enc4 != 64) {
	                output = output + String.fromCharCode(chr3);
	            }
	        }
	        output = _utf8_decode(output);
	        return output;
	    }

	    // private method for UTF-8 encoding
	    _utf8_encode = function (string) {
	        string = string.replace(/\r\n/g,"\n");
	        var utftext = "";
	        for (var n = 0; n < string.length; n++) {
	            var c = string.charCodeAt(n);
	            if (c < 128) {
	                utftext += String.fromCharCode(c);
	            } else if((c > 127) && (c < 2048)) {
	                utftext += String.fromCharCode((c >> 6) | 192);
	                utftext += String.fromCharCode((c & 63) | 128);
	            } else {
	                utftext += String.fromCharCode((c >> 12) | 224);
	                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
	                utftext += String.fromCharCode((c & 63) | 128);
	            }

	        }
	        return utftext;
	    }

	    // private method for UTF-8 decoding
	    _utf8_decode = function (utftext) {
	        var string = "";
	        var i = 0;
	        var c = c1 = c2 = 0;
	        while ( i < utftext.length ) {
	            c = utftext.charCodeAt(i);
	            if (c < 128) {
	                string += String.fromCharCode(c);
	                i++;
	            } else if((c > 191) && (c < 224)) {
	                c2 = utftext.charCodeAt(i+1);
	                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
	                i += 2;
	            } else {
	                c2 = utftext.charCodeAt(i+1);
	                c3 = utftext.charCodeAt(i+2);
	                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
	                i += 3;
	            }
	        }
	        return string;
	    }
	}
	/* 时间格式化 */
	function dateFormat(fmt, date) {
	    let ret;
	    let opt = {
	        "Y+": date.getFullYear().toString(),        // 年
	        "m+": (date.getMonth() + 1).toString(),     // 月
	        "d+": date.getDate().toString(),            // 日
	        "H+": date.getHours().toString(),           // 时
	        "M+": date.getMinutes().toString(),         // 分
	        "S+": date.getSeconds().toString()          // 秒
	        // 有其他格式化字符需求可以继续添加，必须转化成字符串
	    };
	    for (let k in opt) {
	        ret = new RegExp("(" + k + ")").exec(fmt);
	        if (ret) {
	            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
	        };
	    };
	    return fmt;
	}

	/*'yyyy-MM-dd HH:mm:ss'格式的字符串转日期*/



	function checkBox(tablecheckBox){
	    tablecheckBox.find("input[name='btSelectAll']").each(function (i) {
	        var $check = $(this);
	        if ($check.attr("id") && $check.next("label")) {
	            return;
	        }
	        var name = $check.attr("name");
	        var id = name + "-all-" + i;
	        var $label = $('<label for="' + id + '"></label>');
	        $check.attr("id", id).parent().addClass("bella-checkbox").append($label);
	    });
	    tablecheckBox.find('tr input[name="btTimeItem"]').each(function (i) {
	        var $check = $(this)
	        if ($check.attr("id") && $check.next("label")) {
	            return;
	        }
	        $check.next().remove();
	        var name = $check.attr("name");
	        var id = name + "-" + i;
	        var $label = $('<label for="' + id + '"></label>');
	        $check.attr("id", id).parent().addClass("bella-checkbox").append($label);
	    });
	}

	/* 数组去重 */
	function uniqueArray(array, key){
	  var result = [array[0]];
	  for(var i = 1; i < array.length; i++){
	    var item = array[i];
	    var repeat = false;
	    for (var j = 0; j < result.length; j++) {
	      if (item[key] == result[j][key]) {
	        repeat = true;
	        break;
	      }
	    }
	    if (!repeat) {
	      result.push(item);
	    }
	  }
	  return result;
	}

	/* 休眠 */
	function sleep(numberMillis) {
		var now = new Date();
		var exitTime = now.getTime() + numberMillis;
		while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
		return;
		}
	}
	var noticeType = "";
	var noticeValue = "";
	//通知部分
	function loadTaskLeftTable(){
		var taskList = [{id:'-1',name:'全部通知'},
			{id:'0',name:'语音通知'},
			{id:'1',name:'短信通知'},
			{id:'2',name:'语音及短信通知'},
			{id:'3',name:'未接通短信通知'}]
		$("#procitytree").hide();
		$("#treetable").bootstrapTable('destroy')
		$("#treetable").bootstrapTable({
			cache:false,
			data:taskList,
			clickToSelect:true,
			uniqueId:'id',
			showColumns: false,
			scrollbar:true,
			columns:[{
				field:'name',
				formatter:function(value,item,index){

					var html = "<label class='glyphicon glyphicon-flash'></label>"+value;
					return html;

				}
			}],
			onClickCell:function(field,value,row,$element){
				$(".tow_nav").html(value)
				var type = "";
				if(value=='全部通知'){
					type="-1"
				}else if(value == '语音通知'){
					type='0'
				}else if(value == '短信通知'){
					type='1'
				}else if(value == '语音及短信通知'){
					type = '2'
				}else if(value == '未接通短信通知'){
					type = '3'
				}
				noticeType = type;
				noticeValue = value;
				//生成表格
				generNoticeTable()
			}
		})
	}
	function loadNoticeTaskData(request) {
		let data = [];
		let url = httpProto+"://"+host+"/control/api_v2.2.5/notice/query/queryAll.json";
		$.ajax({
			type: "get",
			url: url,
			//url: httpProto+"://"+"127.0.0.1:8080"+"/control/20180628/infs/getBroadTask.json",
			data:request.data,
			contentType:"application/json",
			async:false,
			headers: {
				'Authorization': authForAll
			},
			success: function(jsonStr){
				if(jsonStr.code == 200){
					data = jsonStr.data
					//处理数据
					processNoticeData(data.list)
					request.success({
						total: data.totalCount,
						rows: data.list
					})
				}
			},
			error:function(){
				$.alert('查询出错!');
			}
		});

		return data;
	}
	function processNoticeData(data) {
		if(data.length<0){
			console.log("无数据!")
		}
		for(let i = 0; i < data.length; i++){
			data[i].send_status = data[i].status+"";
			data[i].id = data[i].id+"";
			data[i].notice_type = data[i].noticeType+"";


			data[i].notice_status = noticeStatus(data[i].send_status)
			data[i].notice_show = noticeTypeFun(data[i].notice_type)
			data[i].notice_time = "";
			data[i].volume = data[i].volume-5;

			if(data[i].times && data[i].times[0]){
				data[i].timeType = data[i].times[0].timeType+''
				data[i].playing_time = data[i].times[0].playingTime+''
				if('2' == data[i].timeType){
					let timeList = [];
					data[i].times.forEach(newItem => {
						let paramNew = {
							"week_day":newItem.weekDay+"",
							"week_time":newItem.weekTime+"",
						}
						timeList.push(paramNew);
					})
					data[i].callout_time = timeList
				}
			}

			if (data[i].timeType === '2' && data[i].callout_time) {
				let str = ''
				let arr = data[i].callout_time
				for (let j = 0; j < arr.length; j++) {
					switch (arr[j].week_day) {
						case "0":
							str += "每周日、"
							break
						case "1":
							str += "每周一、"
							break
						case "2":
							str += "每周二、"
							break
						case "3":
							str += "每周三、"
							break
						case "4":
							str += "每周四、"
							break
						case "5":
							str += "每周五、"
							break
						case "6":
							str += "每周六、"
							break
					}
				}
				data[i].notice_time = str.substring(0, str.length - 1)
			} else {
				data[i].notice_time = data[i].playing_time
			}
			// data[i].notice_call_pre = transferPer(data[i].tot_call_rate)
			// data[i].notice_uncall_pre = transferPer(data[i].tot_uncall_rate)
			// data[i].notice_answer_pre = transferPer(data[i].tot_answer_rate)
			data[i].notice_type = noticeTypeFun(data[i].playType+"")
			data[i].notice_model = noticeModel(data[i].type+"")
			data[i].b_en = data[i].bEnable+'' === '1' ? "已启用" : "未启用"
		}
	}
	function noticeModel(model) {
		switch (model) {
			case '1':
				return '文字通知'
			case '2':
				return '录音通知'
		}
	}
	function transferPer(per) {
		if (!per || per === '0') return '0%'
		let float = Number(per)
		return (float * 100).toFixed(2) + '%'
	}
	function noticeStatus(status) {
		switch (status) {
			case '0':
				return '未开始'
			case '1':
				return '开始'
			case '2':
				return '进行中'
			case '3':
				return '结束'
			case '4':
				return '暂停'
			case '5':
				return '部分失败'
			default:
				return ''
		}
	}
	function noticeTypeFun(type) {
		switch (type) {
			case '0':
				return '即时通知'
			case '1':
				return '定时通知'
			case '2':
				return '触发通知'
		}
	}
	function generNoticeTable() {
		let column = [{
			checkbox:true
		},{
			field:'name',
			title:'名称'
		},{
			field:'notice_status',
			title:'执行状态'
		},{
			field:'notice_type',
			title:'类型',
		},{
			field:'notice_time',
			title:'启动时间',
		},{
			field:'accessNum',
			title:'接入号码',
		},{
			field:'pstnNum',
			title:'显示号码'
		},{
			field:'totalCust',
			title:'呼叫数'
		},{
			field:'totalCall',
			title:'已呼数'
		},{
			field:'keyNumber',
			title:'按键数'
		},{
			field:'totalUnCall',
			title:'未呼数'
		},{
			field:'volume',
			title:'音量'
		},{
			field:'b_en',
			title:'是否启用'
		}]
		$('#noticeTable').bootstrapTable('destroy')
		$('#noticeTable').bootstrapTable({
			cache:false,
			data:'',
			clickToSelect:true,
			uniqueId:'id',
			showColumns:false,
			scrollbar:true,
			search:false,
			height:'500px',
			autoHeight: true,
			ajax:loadNoticeTaskData,
			queryParams : function (params) {
				//这里的是搜索条件
				let temp = {
					showNumber:"",//显示号码
					status:$('#noticeState option:selected').val(),//执行状态
					playType:$('#searchNoticeType option:selected').val(),
					callCount:"",//呼叫数
					compareCallCount:"",//呼叫数的运算符，>、<、=、<=、=>
					calledCount:"",//已呼数
					compareCalledCount:"",//已呼数的运算符，>、<、=、<=、=>
					accessNum:"",//接入号
					unCallCount:"",//未呼数
					compareUnCallCount:"",//未呼数的运算符，>、<、=、<=、=>
					name:$('#searchNoticeName').val(),
					bEnable:$('#searchNoticeEnable option:selected').val(),
					compareVolume:"",//音量值的运算符，>、<、=、<=、=>
					volume:"",//音量值
					createDateBegin:"",//启动时间的开始
					createDateEnd:"",//启动时间的结束
					noticeType: noticeType == -1 ? "" : noticeType,
					userId:userId,
					currPage:(params.offset / params.limit) + 1,
					pageLimit:params.limit,
				};
				return temp;
			},
			pagination: true,
			pageNumber:1,
			sidePagination:'server',
			pageSize:10,
			pageList:[10, 20, 50, 100],
			rowStyle:function(row,index){
				return "height:30px";
			},
			columns:column
		})
		var contentHeight = getVisible();
		var toolBarH = $('.fixed-table-toolbar').height();
		var height = contentHeight - toolBarH -131;
		var container = $('.fixed-table-container').css({'height':height})
	}

	function getDisplayNumber() {
		$.ajax({
			url:httpProto+"://"+host+"/control/20180628/infs/getPstnNumList.json",
			type:"post",
			data:JSON.stringify({deptId:""}),
			contentType:"application/json",
			dataType:"json",
			async:false,
			success:function(data){
				if (data.statuscode == "000000") {
					let arr = data.pstn_number.split(',')
					let strTwo = "";
					arr.forEach(item => {
						strTwo +="<option value='"+item+"'>"+item+"</option>"
					})
					$("#showNumber").html(strTwo)
				}
			}
		})
	}
	function getNoticeAudioList() {
		$.ajax({
			url:httpProto+"://"+host+"/control/20210928/infs/getMusicStoreList.json",
			type:"post",
			data:JSON.stringify({deptId:deptId,isAdmin:isAdmin,isShowKey:"1"}),
			contentType:"application/json",
			dataType:"json",
			async:false,
			success:function(data){
				if (data.statuscode == "000000") {
					var audioList = data.data
					var strTwo = "<option value=\"\">请选择结束通知音</option>";
					for (var i = 0; i < audioList.length; i++) {
						var audio = audioList[i];
						var value = "";
						var id = "";
						for (var key in audio) {
							if (key=="id"){
								id = audio[key];
							}
							if (key == "audio_name") {
								value=audio[key];
							}
						}
						strTwo +="<option value='"+id+"'>"+value+"</option>"
					}
					$("#endNotice").html(strTwo)
				}
			}
		})
	}
	function showNoticePlayType(flag){
		if(flag){
			$(".noticeType").removeAttr("hidden");
			$(".notice-submit-add").show();
			$('.notice-submit-edit').hide();
		}else {
			$(".noticeType").attr("hidden", "hidden");
			$(".notice-submit-add").hide();
			$('.notice-submit-edit').show();
		}
	}
	
	//更改通知类型的操作
	function changeNotificationType() {
		let v = $("#notificationType option:selected").val();
		if (v == 1) {
			$("#noticeContentDiv").removeAttr("hidden")
			$("#noticeVoicetDiv").attr("hidden", "hidden");
		}else{
			$("#noticeVoicetDiv").removeAttr("hidden")
			$("#noticeContentDiv").attr("hidden", "hidden");
		}
	}
	function changeSmsModal() {
		let value = $('#smsModal option:selected').val();
		value = $('#smsIdInput'+value).val();
		if(value){
			$("#smsContent").val(value);
			$("#smsContent").prop("readonly",true);
		}else{
			$("#smsContent").val("");
			$("#smsContent").prop("readonly",false);
		}
	}
	function changeNoticeType() {
		let v = $("#typeNotice option:selected").val();
		$("#recvBtnDiv").attr("hidden", "hidden");
		$("#smsDiv").attr("hidden", "hidden");
		$("#tryTimeDiv").removeAttr("hidden");
		$("#currentNumDiv").removeAttr("hidden");
		$("#pstnNumDiv").removeAttr("hidden");
		$("#voiceDiv").removeAttr("hidden");
		$("#notificationDiv").removeAttr("hidden");
		$("#recvBtnDiv").removeAttr("hidden");
		if (v == 0) {

		}else if(v == 1){
			$("#recvBtnDiv").attr("hidden", "hidden");
			$("#smsDiv").removeAttr("hidden");
			$("#tryTimeDiv").attr("hidden", "hidden");
			$("#currentNumDiv").attr("hidden", "hidden");
			$("#pstnNumDiv").attr("hidden", "hidden");
			$("#voiceDiv").attr("hidden", "hidden");
			$("#notificationDiv").attr("hidden", "hidden");
		}else if(v == 2){
			$("#smsDiv").removeAttr("hidden");
		}else if(v == 3){
			$("#recvBtnDiv").attr("hidden", "hidden");
			$("#smsDiv").removeAttr("hidden");
		}
	}
	function noticeChangeTimeArea(){
		var radioValue = $('input[name="noticeTimetype"]:checked').val();
		if(radioValue==1){
			$("#noticeTimeinput").removeAttr("hidden")
			$("#noticeTimetable").attr("hidden","hidden")
		}else{
			$("#noticeTimetable").removeAttr("hidden")
			$("#noticeTimeinput").attr("hidden","hidden")
		}
	}
	function generNoticeTimeTable(times){
		if(times == null || times == "" || times == undefined){
			times = []
		}
		var data=[].concat(times)
		$("#noticeBootstrap-table").bootstrapTable("destroy");
		$("#noticeBootstrap-table").bootstrapTable({
			//showFullscreen:true,
			toolbarAlign:'right',
			toolbar:'#noticeToolbar',
			silent:true,
			data:data,
			striped:true,
			cache:false,
			selectItemName:'btTimeItem',
			//showColumns:true,
			clickToSelect:true,
			uniqueId:'index',
			columns:[{
				checkbox:true,
			},{
				field:'index',
				title:'序号'
			},{
				field:'Mon',
				title:'周一'
			},{
				field:'Tue',
				title:'周二'
			},{
				field:'Wed',
				title:'周三'
			},{
				field:'Thu',
				title:'周四'
			},{
				field:'Fri',
				title:'周五'
			},{
				field:'Sat',
				title:'周六'
			},{
				field:'Sun',
				title:'周日'
			}],
			onDblClickCell: function(field,value,row,$element){

				var upIndex = $element[0].parentElement.rowIndex - 1;
				if(field == 'Mon' || field == 'Tue' || field == 'Wed' || field == 'Thu' || field == 'Fri' || field == 'Sat' || field == 'Sun'){
					$element[0].innerHTML="<input id='inputCell' type='text' name='inputCell' style='width:auto;' value='"+value+"'>";
					$("#inputCell").focus();
					$("#inputCell").blur(function(){
						var newValue = $("#inputCell").val();
						row[field] = newValue;
						$(this).remove()
						$("#noticeBootstrap-table").bootstrapTable('updateCell',{
							index:upIndex,
							field:field,
							value:newValue
						});
					})
				}
			}
		})
		$("#bootstrap-table").bootstrapTable('hideColumn', 'index');
		this.checkBox($("#bootstrap-table"))
	}
	function getNoticeData(){
		//表单校验、打包
		let newNotice = {};
		newNotice.name = $('#noticeName').val();
		if(!newNotice.name){
			$.alert('请输入通知名称')
			return
		}
		newNotice.id = $("#noticeId").val();
		newNotice.type = $('#notificationType option:selected').val();
		newNotice.notice_type = $('#typeNotice option:selected').val();
		if (newNotice.notice_type === '1') {
			newNotice.type = '-1'
		}
		newNotice.play_type = $('#playType option:selected').val();
		//短信模块
		newNotice.sms_content = $("#smsContent").val();
		newNotice.dept_id = $("#deptRealIdForNotice").val();
		if (!newNotice.dept_id) {
			newNotice.dept_id = '1' == isAdmin ? '-1' : deptId;
		}
		if (newNotice.notice_type !== '0') {
			if (!newNotice.sms_content) {
				$.alert('短信不能为空')
				return
			}
		}
		let dateNow = new Date();
		newNotice.sys_user_id = userId;
		if(!isNoticeEdit){
			newNotice.status = "0";//当前通知状态，0-未开始，1-开始 2-进行中 3-已结束 4-暂停
		}
		newNotice.volume = $('#volume').slider('getValue')+"";
		newNotice.b_enable = $("#noticeEnable").prop("checked") ? '1' : '0'; //是否启用
		newNotice.access_num = $('#pstnNum option:selected').val();
		//触发广播，通知接入号不能为空
		if (newNotice.play_type == "2" && !newNotice.access_num) {
			$.alert('通知接入号不能为空')
			return
		}
		newNotice.access_num_pw = $("#noticePassword").val();
		newNotice.recv_btn = $("#recvBtn").prop("checked");
		newNotice.dtmf_key = $('#recvBtnValue option:selected').val();
		//不采集按键时清空 1:不启用采集按键 2：通知方式不为语音通知、不为语音通知及短信
		//不记录按键数，清空或者值为0
		if (!newNotice.recv_btn || (newNotice.notice_type != '0' && newNotice.notice_type != '2')) {
			newNotice.dtmf_key = ''
			newNotice.prompt_tone = '0'
		}
		newNotice.redial_times = $('#tryTimes').val();
		newNotice.max_concurrent_num = $('#currentNum').val();
		newNotice.pstn_num = $('#showNumber').val();
		newNotice.max_ring_time = $('#ringTimes').val();
		//采集按键，但是结束通知音为空，且为语音通知
		//不记录结束提示音，清空
		if (newNotice.notice_type !== '1') {
			if (!newNotice.redial_times) {
				$.alert('重试次数不能为空')
				return
			}
			if (!newNotice.max_concurrent_num) {
				$.alert('并发线数不能为空')
				return
			}
			if (!newNotice.pstn_num) {
				$.alert('显示号码不能为空')
				return
			}
			if (!newNotice.max_ring_time) {
				$.alert('振铃时长不能为空')
				return
			}
			newNotice.text = $('#noticeContent').val();
			newNotice.audio_id = $('#noticeVoice option:selected').val();
			if (newNotice.type === '1') {
				if (!newNotice.text) {
					$.alert('文字内容不能为空')
					return
				}
				newNotice.audio_id = ''
			} else if (newNotice.type === '2') {
				if (!newNotice.audio_id) {
					$.alert('录音文件不能为空')
					return
				}
			}
		}
		newNotice.prompt_tone = $('#endNotice option:selected').val();
		newNotice.prompt_tone = newNotice.prompt_tone ? newNotice.prompt_tone : '0';
		let notice_time_list = $('#noticeBootstrap-table').bootstrapTable('getData')
		let notice_time = []
		for (let i = 0; i < notice_time_list.length; i++) {
			let btime = notice_time_list[i]
			for(let key in btime){
				if(btime[key] != ''){
					if(key == 'Fri'){
						notice_time.push({"week_day":"4","week_time":btime[key]})
					}
					if(key == 'Mon'){
						notice_time.push({"week_day":"0","week_time":btime[key]})
					}
					if(key == 'Thu'){
						notice_time.push({"week_day":"3","week_time":btime[key]})
					}
					if(key == 'Tue'){
						notice_time.push({"week_day":"1","week_time":btime[key]})
					}
					if(key == 'Wed'){
						notice_time.push({"week_day":"2","week_time":btime[key]})
					}
					if(key == 'Sat'){
						notice_time.push({"week_day":"5","week_time":btime[key]})
					}
					if(key == 'Sun'){
						notice_time.push({"week_day":"6","week_time":btime[key]})
					}
				}

			}
		}
		newNotice.callout_time = notice_time;
		newNotice.timetype = $('input[name="noticeTimetype"]:checked').val();
		newNotice.playing_time = $('#noticePlaytime').val();
		if (newNotice.play_type === '1') {
			if (newNotice.timetype === '1') {
				if (!newNotice.playing_time) {
					$.alert('通知时间不能为空')
					return
				} else {
					if (newNotice.playing_time instanceof Date) {
						newNotice.playing_time = getFormatDate('YYYY-mm-dd HH:MM:SS', newNotice.playing_time)
					}
				}
			} else if (newNotice.timetype === '2') {
				if (newNotice.callout_time.length < 1) {
					$.alert('循环时间不能为空')
					return
				}
			}
		} else if (newNotice.play_type === '2') {
			if (!newNotice.access_num) {
				$.alert('接入号不能为空')
				return
			}
		} else if (newNotice.play_type === '0') {
			newNotice.playing_time = dateNow.toLocaleTimeString();
		}
		newNotice.part_id = $("#isSelectNum").val();
		if (!newNotice.part_id) {
			$.alert('通知号码不能为空')
			return
		}
		if (newNotice.notice_type === '1') {
			newNotice.type = '-1'
		}
	return JSON.stringify(newNotice)
}


	//自检模块
	function loadSelfCheckLeftTable(){
		var taskList = [{id:'0',name:'即时自检'},
			{id:'1',name:'定时自检'}]
		$("#procitytree").hide();
		$("#treetable").bootstrapTable('destroy')
		$("#treetable").bootstrapTable({
			cache:false,
			data:taskList,
			clickToSelect:true,
			uniqueId:'id',
			showColumns: false,
			scrollbar:true,
			columns:[{
				field:'name',
				formatter:function(value,item,index){
					var html = "<label class='glyphicon glyphicon-flash'></label>"+value;
					return html;
				}
			}],
			onClickCell:function(field,value,row,$element){
				$(".tow_nav").html(value)
				var type = "";
				if(value=='即时自检'){
					type="0"
				}else if(value == '定时自检'){
					type='1'
				}
				checkType = type;
				checkValue = value;
				//生成表格
				generCheckTable()
			}
		})
	}
	function loadSelfCheckData(request){
		let url = httpProto+"://"+host+"/control/api_v2.2.5/selfCheck/queryAll.json";
		$.ajax({
			type: "post",
			url: url,
			//url: httpProto+"://"+"127.0.0.1:8080"+"/control/20180628/infs/getBroadTask.json",
			data: JSON.stringify(request.data),
			contentType:"application/json",
			headers:{
				'Authorization':authForAll
			},
			async:false,
			success: function(jsonStr){
				if(jsonStr.code == 200){
					data = jsonStr.data
					//处理数据
					processCheckData(data.list)
					request.success({
						total: data.totalCount,
						rows: data.list
					})
				}
			},
			error:function(){
				$.alert('查询出错!');
			}
		});
	}
	function processCheckData(data) {
		if(data.length<0){
			console.log("无数据!")
		}
		for(let i = 0; i < data.length; i++){
			data[i].s_status = broadStatus(data[i].status+'')
			data[i].timeMode = selfTimeType(data[i].timeType+'')
			data[i].b_en = data[i].bEnable+"" === '1' ? "已启用" : "未启用"
			if (data[i].timeType + '' === '2') {
				let str = ''
				let arr = selfCheckCycle(data[i].playCycle.split(','))
				arr.forEach(it => {
					str += "每" + it + '、'
				})
				data[i].cycle = str.substring(0, str.length - 1)
			} else {
				data[i].cycle = data[i].playTime
			}
		}
	}
	function selfCheckCycle(data) {
		if (!data)return
		let str = []
		let dayOfWeek = new Array('周一','周二','周三','周四','周五','周六','周日')
		data.forEach(item => {
			str.push(dayOfWeek[Number(item)])
		})
		return Array.from(new Set([...str]))
	}
	function selfTimeType(num) {
		switch (num) {
			case '1':
				return '固定'
			case '2':
				return '循环'
			default:
				return ''
		}
	}
	function broadStatus(status) {
		switch (status) {
			case '0':
				return '未开始'
			case '1':
				return '开始'
			case '2':
				return '进行中'
			case '3':
				return '结束'
			case '4':
				return '暂停'
			case '5':
				return '部分失败'

			default:
				return ''
		}
	}
	function startCheckTask() {
		//执行任务
		let row = $("#checkTable").bootstrapTable("getSelections");
		if(row.length > 1 || row.length <= 0){
			$.alert('请选择一条自检任务')
			return;
		}
		let id = row[0].id;
		var base = new Base64();
		var Authorization = base.encode(username+":"+password)
		$.ajax({
			type: "post",
			url: httpProto+'://'+host+'/control/api_v1.0/selfCheck/setStatus.json',
			data: JSON.stringify({"id": id,"status":'1'}),
			contentType:"application/json",
			headers:{
				'Authorization':Authorization
			},
			async:false,
			success: function(jsonStr){
				if(jsonStr.code == 200){
					$.alert('启动成功!');
					setTimeout(function () {
						//生成表格
						generCheckTable()
					},2000);
				}
			},
			error:function(){
				$.alert('启动失败!');
			}
		});
	}
	function generCheckTable(data) {
		let column = [{
			checkbox:true
		},{
			field:'name',
			title:'名称'
		},{
			field:'s_status',
			title:'状态'
		},{
			field:'startTime',
			title:'执行时间'
		},{
			field:'allCount',
			title:'检测总数'
		},{
			field:'normalCount',
			title:'正常数'
		},{
			field:'abnormalCount',
			title:'不正常数'
		}]
		if(checkType == '1'){
			column = [{
				checkbox:true
			},{
				field:'name',
				title:'名称'
			},{
				field:'s_status',
				title:'状态'
			},{
				title: '模式',
				field: 'timeMode',
			},{
				title: '执行周期',
				field: 'cycle',
			},{
				field:'startTime',
				title:'执行时间'
			},{
				field:'allCount',
				title:'检测总数'
			},{
				field:'normalCount',
				title:'正常数'
			},{
				field:'abnormalCount',
				title:'不正常数'
			},{
				field:'b_en',
				title:'是否启用'
			}]
		}
		$('#checkTable').bootstrapTable('destroy')
		$('#checkTable').bootstrapTable({
			cache:false,
			data:data,
			clickToSelect:true,
			uniqueId:'id',
			showColumns:false,
			scrollbar:true,
			search:false,
			height:'500px',
			autoHeight: true,
			ajax:loadSelfCheckData,
			queryParams : function (params) {
				//这里的是搜索条件
				let temp = {
					deptId:deptId,
					timeType:"",//模式 仅支持定时自检
					startTimeBegin:"",//执行时间开始
					startTimeEnd:"",//执行时间结束
					allCount:"",//检测总数
					compareAllCount:"",//检测总数运算符 >、<、=、<=、=>
					normalCount:"",//正常数
					compareNormalCount:"",//正常数运算符 >、<、=、<=、=>
					abnormalCount:"",//不正常数
					compareAbnormalCount:"",//不正常数运算符 >、<、=、<=、=>
					bEnable:"",//是否启用 仅支持定时自检
					playType:checkType,
					name:$('#searchCheckName').val(),
					status: $('#checkState option:selected').val(),//状态
					userId:userId,
					currPage:(params.offset / params.limit) + 1,
					pageLimit:params.limit,
				};
				return temp;
			},
			pagination: true,
			pageNumber:1,
			sidePagination:'server',
			pageSize:10,
			pageList:[10, 20, 50, 100],
			rowStyle:function(row,index){
				return "height:30px";
			},
			columns:column
		})
		var contentHeight = getVisible();
		var toolBarH = $('.fixed-table-toolbar').height();
		var height = contentHeight - toolBarH -131;
		var container = $('.fixed-table-container').css({'height':height})
	}
	function doDeleteCheckTask(id) {
		let flag = false
		var base = new Base64();
		var Authorization = base.encode(username+":"+password)
		$.ajax({
			url:httpProto+"://"+host+"/control/api_v1.0/selfCheck/delete.json",
			type: "get",
			data:{"id":id},
			dataType:"json",
			async:false,
			headers:{
				'Authorization':Authorization
			},
			contentType:"application/json",
			success:function(data){
				if (data.statuscode = "000000") {
					flag = true
				}else{
					flag = false;

				}
			}

		})
		return flag
	}
	function deleteCheckTask() {
		let row = $("#checkTable").bootstrapTable("getSelections");
		if(row.length > 1 || row.length <= 0){
			$.alert('请选择一条自检任务')
			return;
		}
		let id = row[0].id;
		$.confirm({
			title:'确认删除',
			content:'确认删除此自检任务?',
			buttons:{
				确认:function(){
					var f = doDeleteCheckTask(id)
					if(f){
						$.alert("删除成功!");
						//生成表格
						generCheckTable()
					}else{
						$.alert("删除失败!");
					}
				},
				取消: function(){}
			}
		})
	}
	function batchDelCheck() {
		let row = $("#checkTable").bootstrapTable('getSelections')
		if(row.length <= 0){
			$.alert('请选择自检任务')
			return;
		}
		$.confirm({
			title:'确认删除',
			content:'确认删除'+row.length+'条自检任务?',
			buttons:{
				确认:function(){
					var fail = []
					for(var i = 0; i < row.length; i++){
						var f = doDeleteCheckTask(row[i].id)
						if(!f){
							fail.push(row[i].id)
						}
					}
					if(fail.length<=0){
						$.alert("删除成功!");
					}else{
						$.alert(fail+"删除失败!");
					}
					//生成表格
					generCheckTable()
				},
				取消:function(){}
			}
		})
	}
	function updateCheckTask() {
		let row = $("#checkTable").bootstrapTable('getSelections')
		if(row.length > 1 || row.length <= 0){
			$.alert('请选择一条自检任务')
			return;
		}
		let id = row[0].id
		isCheckEdit = true;
		showCheckPlayType(false)
		refreshTreeCheck();
		getCheckByID(id);
	}
	function addCheckTask() {
		$("#checkEnableDiv").attr("hidden", "hidden");
		$("#checkPlayTimeDiv").attr("hidden", "hidden");
		$("#CheckTimeDiv").attr("hidden", "hidden");
		//标识是添加操作
		isCheckEdit = false;
		let dateNow = new Date();
		$("#checkPlaytime").val(dateFormat('YYYY-mm-dd HH:MM:SS',dateNow));
		showCheckPlayType(true)
		$('#myCheckModalLabel').html('添加自检任务')
		refreshTreeCheck();
		generCheckTimeTable(null);
		$("#editCheckModal").modal("show");
		generFromData("","C");
		showTimeArea();
		$("#deptRealIdForCheck").val('-2');
		$("#deptInputForCheck").val("全部区域");
		if('1' == isAdmin){
			$("#deptRealIdForCheck").val('-1');
			$("#deptInputForCheck").val("仅管理员可见");
		}else if(deptIdName){
			$("#deptRealIdForCheck").val(deptId);
			$("#deptInputForCheck").val(deptIdName);
		}
	}
	function showCheckPlayType(flag){
		if(flag){
			$(".checkType").removeAttr("hidden");
			$(".check-submit-add").show();
			$('.check-submit-edit').hide();
		}else {
			$(".checkType").attr("hidden", "hidden");
			$(".check-submit-add").hide();
			$('.check-submit-edit').show();
		}
	}
	function generCheckTimeTable(times){
		if(times == null || times == "" || times == undefined){
			times = []
		}
		var data=[].concat(times)
		$("#checkBootstrap-table").bootstrapTable("destroy");
		$("#checkBootstrap-table").bootstrapTable({
			//showFullscreen:true,
			toolbarAlign:'right',
			toolbar:'#checkToolbar',
			silent:true,
			data:data,
			striped:true,
			cache:false,
			selectItemName:'btTimeItem',
			//showColumns:true,
			clickToSelect:true,
			uniqueId:'index',
			columns:[{
				checkbox:true,
			},{
				field:'index',
				title:'序号'
			},{
				field:'Mon',
				title:'周一'
			},{
				field:'Tue',
				title:'周二'
			},{
				field:'Wed',
				title:'周三'
			},{
				field:'Thu',
				title:'周四'
			},{
				field:'Fri',
				title:'周五'
			},{
				field:'Sat',
				title:'周六'
			},{
				field:'Sun',
				title:'周日'
			}],
			onDblClickCell: function(field,value,row,$element){

				var upIndex = $element[0].parentElement.rowIndex - 1;
				if(field == 'Mon' || field == 'Tue' || field == 'Wed' || field == 'Thu' || field == 'Fri' || field == 'Sat' || field == 'Sun'){
					$element[0].innerHTML="<input id='inputCell' type='text' name='inputCell' style='width:auto;' value='"+value+"'>";
					$("#inputCell").focus();
					$("#inputCell").blur(function(){
						var newValue = $("#inputCell").val();
						row[field] = newValue;
						$(this).remove()
						$("#checkBootstrap-table").bootstrapTable('updateCell',{
							index:upIndex,
							field:field,
							value:newValue
						});
					})
				}
			}
		})
		$("#checkBootstrap-table").bootstrapTable('hideColumn', 'index');
		this.checkBox($("#checkBootstrap-table"))
	}
	function getCheckByID(taskId) {
		var base = new Base64();
		var Authorization = base.encode(username+":"+password)
		$.ajax({
			url:httpProto+"://"+host+"/control/api_v1.0/selfCheck/getDetail.json",
			// url:httpProto+"://"+"localhost:8090"+"/control/api_v1.0/selfCheck/getDetail.json",
			type:"get",
			data:{"id":taskId},
			dataType:"json",
			async:false,
			contentType:"application/json",
			beforeSend:function(request){
				request.setRequestHeader("Authorization",Authorization)
			},
			success:function(data){
				if (data.statuscode="000000"){
					setCheckData(data.data);
					$('#myCheckModalLabel').html('编辑自检任务')
					$("#editCheckModal").modal("show");
				} else{
					$.alert("获取数据出错!");
				}
			}
		})
	}
	function setCheckData(data) {
		set_select_checked("checkType",data.playType)
		let timeType = "";
		if (data.testTimes.length > 0) {
			timeType = data.testTimes[0].timeType+''
			if(timeType == '1'){
				$('#checkPlaytime').val(data.testTimes[0].playingTime);
			}
		}
		if(data.custlists && data.custlists.length > 0){
			let importArr = [];
			data.custlists.forEach(item => {
				importArr.push(item.telNumber)
			})
			generFromData(importArr.toString(),"C");
		}
		$("#checkTimetype"+timeType).click();
		$('#checkName').val(data.name);
		$("#checkId").val(data.id);
		let checkDeptId = data.deptId ? data.deptId : "";
		$("#deptRealIdForCheck").val(checkDeptId);
		let dept_name = '' == checkDeptId || '0' == checkDeptId ? '全部区域' : '-1' == checkDeptId ? '仅管理员可见' : data.deptName;
		$("#deptInputForCheck").val(dept_name);
		$("#checkEnable").prop("checked",data.bEnable+"" === '1');
		generCheckTimeTable("");
		if(timeType == '2'){
			let newCallOutTime = produceTimeData(data.testTimes);
			generCheckTimeTable(newCallOutTime);
		}
		checkChangeTimeArea();
		showTimeArea();
	}
	function checkChangeTimeArea(){
		var radioValue = $('input[name="checkTimetype"]:checked').val();
		if(radioValue==1){
			$("#checkTimeinput").removeAttr("hidden")
			$("#checkTimetable").attr("hidden","hidden")
		}else{
			$("#checkTimetable").removeAttr("hidden")
			$("#checkTimeinput").attr("hidden","hidden")
		}
	}
	var transferCheck = null;
	function initCheckTransfer(data,data1){
		transferCheck = new Transfer()
		//显示搜索框
		transferCheck.render({
			elem: '#checkTransferContainer',
			// 全部数据
			data: data,
			width:400,
			// 已选择数据，默认在右边
			value:data1 ? data1 : [],
			title: ['待选分机', '已选分机'],
			// 是否展示关键词搜索
			showSearch: true,
			// 初始化的所有菜单在 右侧 ,默认 左侧
			isRight:false,
			// 菜单二级全展开
			spread:true
		})
	}
	function checkSubmitAdd() {
		let data = getCheckData();
		if(!data){
			return;
		}
		var base = new Base64();
		var Authorization = base.encode(username+":"+password)
		$.ajax({
			url:httpProto+'://'+host+'/control/api_v1.0/selfCheck/add.json',
			dataType:'json',
			type:'post',
			data:data,
			contentType:'application/json',
			headers:{
				"Authorization":Authorization
			},
			success:function(result){
				if(result.code == 200){
					$.alert('添加成功！')
					//生成表格
					generCheckTable()
				}else{
					$.alert('添加失败')
				}
				$('#closeCheck').click();
			}
		})
	}
	function checkSubmitEdit() {
		let data = getCheckData();
		if(!data){
			return;
		}
		var base = new Base64();
		var Authorization = base.encode(username+":"+password)
		$.ajax({
			url:httpProto+'://'+host+'/control/api_v1.0/selfCheck/update.json',
			dataType:'json',
			type:'post',
			data:data,
			contentType:'application/json',
			headers:{
				"Authorization":Authorization
			},
			success:function(result){
				if(result.code == 200){
					$.alert('编辑成功！')
					//生成表格
					generCheckTable()
				}else{
					$.alert('编辑失败')
				}
				$('#closeCheck').click();
			}
		})
	}
	function getCheckData(){
		//表单校验、打包
		let newCheckData = {};
		newCheckData.name = $('#checkName').val();
		if(!newCheckData.name){
			$.alert('请输入自检任务名称')
			return
		}
		newCheckData.id = $("#checkId").val();
		newCheckData.deptId = $("#deptRealIdForCheck").val();
		if (!newCheckData.deptId) {
			newCheckData.deptId = '1' == isAdmin ? '-1' : deptId;
		}
		newCheckData.playType = $('#checkType option:selected').val();
		newCheckData.sysUserId = userId;
		newCheckData.bEnable = $("#checkEnable").prop("checked") ? '1' : '0'; //是否启用
		//不记录结束提示音，清空
		let notice_time_list = $('#checkBootstrap-table').bootstrapTable('getData')
		let notice_time = []
		for (let i = 0; i < notice_time_list.length; i++) {
			let btime = notice_time_list[i]
			for(let key in btime){
				if(btime[key] != ''){
					if(key == 'Fri'){
						notice_time.push({"week_day":"4","week_time":btime[key]})
					}
					if(key == 'Mon'){
						notice_time.push({"week_day":"0","week_time":btime[key]})
					}
					if(key == 'Thu'){
						notice_time.push({"week_day":"3","week_time":btime[key]})
					}
					if(key == 'Tue'){
						notice_time.push({"week_day":"1","week_time":btime[key]})
					}
					if(key == 'Wed'){
						notice_time.push({"week_day":"2","week_time":btime[key]})
					}
					if(key == 'Sat'){
						notice_time.push({"week_day":"5","week_time":btime[key]})
					}
					if(key == 'Sun'){
						notice_time.push({"week_day":"6","week_time":btime[key]})
					}
				}

			}
		}
		newCheckData.taskTime = notice_time;
		newCheckData.timeType = $('input[name="checkTimetype"]:checked').val();
		newCheckData.playingTime = $('#checkPlaytime').val();
		if (newCheckData.playType === '1') {
			if (newCheckData.timeType === '1') {
				if (!newCheckData.playingTime) {
					$.alert('自检时间不能为空')
					return
				}
			} else if (newCheckData.timeType === '2') {
				if (newCheckData.taskTime.length < 1) {
					$.alert('循环时间不能为空')
					return
				}
			}
		}
		let part_id_arr = transferCheck.getTransferData();
		let partIds = [];
		partIds = getAllNodeId(partIds, part_id_arr)
		newCheckData.extens = partIds.toString();
		if(!newCheckData.extens){
			$.alert("请选择分机");
			return;
		}
		return JSON.stringify(newCheckData)
	}
	function exportExcel() {
		let row = $("#checkTable").bootstrapTable("getSelections");
		let id = row[0].id && row[0].id != "checkTable" ? row[0].id : "";
		let param={
			taskId:id,
			extens:checkExtens && checkExtens.length != 0 ? checkExtens : "",
			employeeName:$("#searchEmployeeName").val(),
			telNumber:$("#searchTelNumber").val(),
			upTimeBegin:"",//结束时间开始
			upTimeEnd:"",//结束时间结束
			echoTimeBegin:"",//开始时间开始
			echoTimeEnd:"",//开始时间结束
			echoResult:$('#resultList option:selected').val(),
		};
		let url=httpProto+"://"+host+"/control/api_v2.2.5/selfCheck/exportList.json";
		let xhr = new XMLHttpRequest();
		xhr.open('POST', url, true);
		xhr.setRequestHeader("Content-Type", 'application/json;charset=utf-8');
		xhr.setRequestHeader("Authorization", authForAll);
		xhr.responseType = 'blob';
		xhr.onload = function (res) {
			if (this.readyState == 4 && this.status == 200) {
				const link = document.createElement('a')
				const blob = new Blob([xhr.response], {
					type: 'application/vnd.ms-excel'
				})
				link.style.display = 'none'
				link.href = URL.createObjectURL(blob)
				link.download = xhr.getResponseHeader("Content-Disposition").split(";")[1].split("filename=")[1] //下载的文件名
				document.body.appendChild(link)
				link.click()
				document.body.removeChild(link)
				return false;
			}
		};
		//参数是json格式
		xhr.send(JSON.stringify(param));
		// $.ajax({
		// 	// url:httpProto+"://"+host+"/control/api_v2.2.5/selfCheck/exportList.json",
		// 	url:url,
		// 	type: "post",
		// 	data:JSON.stringify(param),
		// 	dataType:"json",
		// 	async:false,
		// 	headers:{
		// 		"Authorization":authForAll
		// 	},
		// 	contentType:"application/json",
		// 	success: function(response, status, request) {
		// 		let ret_data = JSON.parse(response)
		// 		let path = ret_data['path']
		// 		let filename = ret_data['filename']
		//
		// 		var form = $('<form method="POST" action="'+url+'">');
		// 		form.append($('<input type="hidden" name="path" value="' + path + '">'));
		// 		form.append($('<input type="hidden" name="filename" value="' + filename + '">'));
		// 		$('body').append(form)
		// 		form.submit();
		// 		$("input[name='export']").prop('disabled', false);
		// 		$("input[name='export']").val('导出');
		// 	}
		// })
	}
	function getCheckTaskDetailForProp(request) {
		let url = "";
		var type = $("#checkDetailtype option:selected").val();
		if('2' == type+""){
			url = httpProto+"://"+host+"/control/api_v1.0/selfCheck/history/resultByExtensForPage.json";
			// url = "http://localhost:8090/control/api_v1.0/selfCheck/history/resultByExtensForPage.json";
		}else{
			url = httpProto+"://"+host+"/control/api_v1.0/selfCheck/getResultByExtensForPage.json";
			// url = "http://localhost:8090/control/api_v1.0/selfCheck/getResultByExtensForPage.json";
		}
		$.ajax({
			url:url,
			type: "post",
			data:JSON.stringify(request.data),
			dataType:"json",
			async:false,
			headers:{
				"Authorization":authForAll
			},
			contentType:"application/json",
			success:function(response){
				if (response.code === 200) {
					let newData = response.data;
					let data = newData.list;
					if(data && data.length > 0){
						for (let i = 0; i < data.length; i++) {
							data[i].result = echoResultLocal(data[i].echoResult)
							data[i].tip = abnormalTip(data[i].echoResult)
						}
					}
					request.success({
						total: newData.totalCount,
						rows: data
					})
					$("#checkDetail").modal("show");
				}
			}

		})
	}
	function getCheckTaskDetail(request) {
		let row = $("#checkTable").bootstrapTable("getSelections");
		let url = "";
		var type = $("#checkDetailtype option:selected").val();
		if('2' == type+""){
			url = httpProto+"://"+host+"/control/api_v1.0/selfCheck/history/resultForPage.json";
		}else{
			url = httpProto+"://"+host+"/control/api_v1.0/selfCheck/getResultForPage.json";
		}
		$.ajax({
			url:url,
			type: "post",
			data:JSON.stringify(request.data),
			dataType:"json",
			async:false,
			headers:{
				"Authorization":authForAll
			},
			contentType:"application/json",
			success:function(response){
				if (response.code === 200) {
					let newData = response.data;
					let data = newData.list;
					if(data && data.length > 0){
						for (let i = 0; i < data.length; i++) {
							data[i].result = echoResultLocal(data[i].echoResult)
							data[i].tip = abnormalTip(data[i].echoResult)
						}
					}
					request.success({
						total: newData.totalCount,
						rows: data
					})
					$("#checkDetail").modal("show");
				}
			}

		})
	}
	function echoResultLocal(result) {
		if (result === '0') {
			return "未开始"
		}else if (result === '1') {
			return "自检中"
		} else if (result === '2') {
			return "正常"
		} else if (result === '3' || result === '4' || result === '5' || result === '6') {
			return "异常"
		}
		return ''
	}
	function abnormalTip(tip) {
		switch (tip) {
			case '3':
				return "设备异常"
			case '4':
				return "设备忙碌"
			case '5':
				return "设备超时"
			case '6':
				return "设备离线"
			default:
				return ''
		}
	}
	function initCheckDetailForProp(dn) {
		if(!dn){
			$.alert('请选择一条自检任务')
			return;
		}
		checkExtens = dn;
		$('#checkDetailTable').bootstrapTable('destroy');
		$('#checkDetailTable').bootstrapTable({
			data:"",
			clickToSelect:true,
			uniqueId:'id',
			toolbarAlign:'right',
			silent:true,
			striped:true,
			cache:false,
			showColumns:false,
			scrollbar:true,
			autoHeight: true,
			pagination: true,
			search: false,
			ajax:getCheckTaskDetailForProp,
			queryParams : function (params) {
				//这里的是搜索条件
				let temp = {
					taskId:"",
					extens:checkExtens,
					employeeName:$("#searchEmployeeName").val(),
					telNumber:$("#searchTelNumber").val(),
					upTimeBegin:"",//结束时间开始
					upTimeEnd:"",//结束时间结束
					echoTimeBegin:"",//开始时间开始
					echoTimeEnd:"",//开始时间结束
					echoResult:$('#resultList option:selected').val(),
					currPage:(params.offset / params.limit) + 1,
					pageLimit:params.limit,
				};
				return temp;
			},
			pageNumber: 1,                      //初始化加载第一页，默认第一页,并记录
			pageSize: 10,
			pageList: [10, 25, 50, 100],
			columns:[{
				field:'telNumber',
				title:'终端',
				align:'center',
				valign: 'middle',
			},{
				field:'employeeName',
				title:'设备名',
				align:'center',
				valign: 'middle',
			},{
				field:'echoTime',
				title:'开始时间',
				align:'center',
				valign: 'middle',
			},{
				field:'upTime',
				title:'结束时间',
				align:'center',
				valign: 'middle',
			},{
				field:'result',
				title:'自检结果',
				align:'center',
				valign: 'middle',
			},{
				field:'tip',
				title:'说明',
				align:'center',
				valign: 'middle',
			}]

		})
		$('#checkDetailTableDiv').css({'height':400})
	}
	function doCheckSelect(){
		if(checkExtens && checkExtens.length > 0){
			initCheckDetailForProp(checkExtens);
		}else{
			initCheckDetail();
		}
	}
	function initCheckDetail() {
		checkExtens = [];
		let row = $("#checkTable").bootstrapTable("getSelections");
		if(row.length > 1 || row.length <= 0){
			$.alert('请选择一条自检任务')
			return;
		}
		$('#checkDetailTable').bootstrapTable('destroy');
		$('#checkDetailTable').bootstrapTable({
			data:"",
			clickToSelect:true,
			uniqueId:'id',
			toolbarAlign:'right',
			silent:true,
			striped:true,
			cache:false,
			showColumns:false,
			scrollbar:true,
			autoHeight: true,
			pagination: true,
			search: false,
			ajax:getCheckTaskDetail,
			queryParams : function (params) {
				//这里的是搜索条件
				let temp = {
					taskId:row[0].id,
					extens:checkExtens,
					employeeName:$("#searchEmployeeName").val(),
					telNumber:$("#searchTelNumber").val(),
					upTimeBegin:"",//结束时间开始
					upTimeEnd:"",//结束时间结束
					echoTimeBegin:"",//开始时间开始
					echoTimeEnd:"",//开始时间结束
					echoResult:$('#resultList option:selected').val(),
					currPage:(params.offset / params.limit) + 1,
					pageLimit:params.limit,
				};
				return temp;
			},
			pageNumber: 1,                      //初始化加载第一页，默认第一页,并记录
			pageSize: 10,
			pageList: [10, 25, 50, 100],
			columns:[{
				field:'telNumber',
				title:'终端',
				align:'center',
				valign: 'middle',
			},{
				field:'employeeName',
				title:'设备名',
				align:'center',
				valign: 'middle',
			},{
				field:'echoTime',
				title:'开始时间',
				align:'center',
				valign: 'middle',
			},{
				field:'upTime',
				title:'结束时间',
				align:'center',
				valign: 'middle',
			},{
				field:'result',
				title:'自检结果',
				align:'center',
				valign: 'middle',
			},{
				field:'tip',
				title:'说明',
				align:'center',
				valign: 'middle',
			}]

		})
		$('#checkDetailTableDiv').css({'height':400})
	}
	function changeCheckDetailType(){
		if(checkExtens && checkExtens.length > 0){
			initCheckDetailForProp(checkExtens);
		}else{
			initCheckDetail();
		}
		var type = $("#checkDetailtype option:selected").val();
		$("#export").hide();
		if('2' == type+""){
			$("#export").show();
		}
		return;
	}
	function alertMessage(data) {
		let noticeType = data.noticeType
		if (noticeType === 2) {
			let dn = data.noticeContent
			if (dn && dn.endsWith(',')) {
				dn = dn.substring(0, dn.length - 1)
			}
			$('.tipsForCheck').initTips({
				title: "自检异常", // head头部显示的标题内容
				message:"<div style='text-align:center'>" +
					"终端："+dn+" 异常<br/>" +
					" <a href=\"javascript:void(null);\" onclick=\"initCheckDetailForProp('"+dn+"')\">点击查看详情</a>" +
					"</div>",// 内容区域 动态生成div时,将根据ajax获取的数据并拼接好的html字符串放到此处即可
				duration:5000, // 提示框停留时间(毫秒为单位)  默认值为5000ms
				space:10, // 通知窗之间上下间隔 单位px(默认值为8)
				firstSpace:8, // 第一个提示框距离页面 上方或(下,左,右)的距离 (默认值为8)
				margin:15, // 提示框 距离左右两边的距离 (默认值15px)
				toastType:'warning',// 提示类型 有四个样式可选 info warning error success(默认info)
				width:300, // 提示框宽度,默认为auto不换行
				limit:5, // 限制提示框数量(默认值为4)
				// timingFun:'linear',// 动画运动曲线(默认值为ease)
				// direction:'right bottom', // 提示框滑出方向默认right bottom
				// type:'click', // 触发方式(内容区域)
				// 上方type属性的事件触发后的回调函数
				// action: function () {
				//     console.log(1)
				// }
			});
		}
	}
	function generFromData(dl,type) {
		let param = {deptId:deptId,isAdmin:isAdmin};
		if('6' == stype){
			param.isOffline = '1';
		}
		if(checkType != '-1'){
			//為0時获取支持自检的终端
			param.isOffline = '0';
		}
		$.ajax({
			url:httpProto+"://"+host+"/control/20210927/infs/getDepetAndEmpList.json",
			type:"post",
			data:JSON.stringify(param),
			contentType:"application/json",
			dataType:"json",
			async:false,
			success:function(result){
				let response = result.apiResult;
				if (response.code === 200) {
					if(!dl){
						type == "B" ? initTransfer(response.data) : type == "C" ? initCheckTransfer(response.data) : initChimeTransfer(response.data);
						return;
					}
					generToData(response.data,dl,type);
				}
			}
		})
	}
	var lostTodata = [];
	function generToData(fromData,_extens,type) {
		let newList = JSON.parse(JSON.stringify(fromData));
		lostToData = _extens.split(",");
		let paramOne = JSON.parse(JSON.stringify(lostToData));
		let toData = getNewTree(newList, paramOne);
		if("0" == isAdmin && lostToData && lostToData.length > 0){
			//不为管理员的情况下存在非自身数据域的数据，根据需求进行是否展示非自身数据域的全部父节点
			let param = {deptId:"0",isAdmin:"1"};
			$.ajax({
				url:httpProto+"://"+host+"/control/20210927/infs/getDepetAndEmpList.json",
				type:"post",
				data:JSON.stringify(param),
				contentType:"application/json",
				dataType:"json",
				async:false,
				success:function(result){
					let response = result.apiResult;
					if (response.code === 200) {
						let newExten = _extens.split(",");
						toData = getNewTree(response.data, newExten);
					}
				}
			})
		}
		let newListTwo = JSON.parse(JSON.stringify(fromData));
		let newFromData = getNewFromData(newListTwo, paramOne);
		type == "B" ? initTransfer(newFromData,toData) : type == "C" ? initCheckTransfer(newFromData,toData) :initChimeTransfer(newFromData,toData);
	}
	function getNewTree (treeList, extens) {
		if(!treeList || treeList.length <= 0){
			return [];
		}
		for (let i = treeList.length - 1; i >= 0; i--) {
			let flag = true;
			if("0" == treeList[i].isDept && extens.findIndex(item => treeList[i].label == item) != -1){
				flag = false;
				let index = lostToData.findIndex((ele) =>{
					return ele === treeList[i].label;
				});
				lostToData.splice(index,1);
			}
			if (treeList[i].children && treeList[i].children.length > 0) {
				treeList[i].children = this.getNewTree(treeList[i].children, extens)
				if(treeList[i].children.length >= 1){
					flag = false;
				}
			}
			if(flag){
				treeList.splice(i,1);
			}
		}
		return treeList
	}
	function getNewFromData (treeList, extens) {
		if(!treeList || treeList.length <= 0){
			return [];
		}
		for (let i = treeList.length - 1; i >= 0; i--) {
			if("0" == treeList[i].isDept && extens.findIndex(item => treeList[i].label == item) != -1){
				treeList.splice(i,1);
				continue;
			}
			if (treeList[i].children && treeList[i].children.length > 0) {
				treeList[i].children = getNewFromData(treeList[i].children, extens)
			}
		}
		return treeList
	}

	function changPlayTimeType() {
		let play_time_type = $('#playTimeType option:selected').val();
		switch (play_time_type) {
			case '0':
				$("#brotimes").attr("hidden","hidden");
				$("#brotime").removeAttr("hidden")
				break
			case '1':
				$("#brotimes").removeAttr("hidden")
				$("#brotime").attr("hidden","hidden");
				break
		}
	}
	//整点报时
	function loadTimeChimeLeftTable(){
		var taskList = [{id:'1',name:'已启用'},
			{id:'0',name:'未启用'}]
		$("#procitytree").hide();
		$("#treetable").bootstrapTable('destroy')
		$("#treetable").bootstrapTable({
			cache:false,
			data:taskList,
			clickToSelect:true,
			uniqueId:'id',
			showColumns: false,
			scrollbar:true,
			columns:[{
				field:'name',
				formatter:function(value,item,index){
					var html = "<label class='glyphicon glyphicon-flash'></label>"+value;
					return html;
				}
			}],
			onClickCell:function(field,value,row,$element){
				$(".tow_nav").html(value)
				var type = "";
				if(value=='未启用'){
					type="0"
				}else if(value == '已启用'){
					type='1'
				}
				chimeType = type;
				chimeValue = value;
				//生成表格
				generChimeTable()
			}
		})
	}
	function loadTimeChimeData(request){
		let data = [];
		let url = httpProto+"://"+host+"/control/api_v2.2.5/chime/query/getAll.json";
		// let url = "http://localhost:8090/control/api_v2.2.5/chime/query/getAll.json";
		$.ajax({
			type: "post",
			url: url,
			data: JSON.stringify(request.data),
			dataType:'json',
			contentType:"application/json",
			headers:{
				'Authorization':authForAll
			},
			async:false,
			success: function(jsonStr){
				if(jsonStr.code == 200){
					data = jsonStr.data.list
					processChimeData(data)
					request.success({
						total: jsonStr.data.totalCount,
						rows: data
					})
				}
			},
			error:function(){
				$.alert('查询出错!');
			}
		});
		return data;
	}
	function processChimeData(data) {
		if(data.length<0){
			console.log("无数据!")
		}
		for(let i = 0; i < data.length; i++){
			data[i].b_en = data[i].bEnable+"" === '1' ? "已启用" : "未启用"
		}
	}
	function generChimeTable(data) {
		let column = [{
			checkbox:true
		},{
			field:'name',
			title:'名称'
		},{
			field:'createDate',
			title:'创建时间'
		},{
			field:'b_en',
			title:'状态'
		},{
			field:'startTime',
			title:'执行时间'
		},{
			field:'volume',
			title:'音量'
		},{
			field:'timesForChime',
			title:'播报时间段'
		}]
		$('#chimeTable').bootstrapTable('destroy')
		$('#chimeTable').bootstrapTable({
			cache:false,
			data:data,
			clickToSelect:true,
			uniqueId:'id',
			showColumns:false,
			scrollbar:true,
			search:false,
			height:'500px',
			autoHeight: true,
			ajax:loadTimeChimeData,
			queryParams : function (params) {
				//这里的是搜索条件
				let temp = {
					userId:userId,
					bEnable:chimeType,
					createDateBegin:"",//创建时间开始
					createDateEnd:"",//创建时间结束
					compareVolume:"",//音量值运算符......
					volume:"",//音量值
					playDateBegin:"",//执行时间开始
					playDateEnd:"",//执行时间结束
					name:$('#searchChimeName').val(),
					currPage:(params.offset / params.limit) + 1,
					pageLimit:params.limit,
				};
				return temp;
			},
			pagination: true,
			pageNumber:1,
			sidePagination:'server',
			pageSize:10,
			pageList:[10, 20, 50, 100],
			rowStyle:function(row,index){
				return "height:30px";
			},
			columns:column
		})
		var contentHeight = getVisible();
		var toolBarH = $('.fixed-table-toolbar').height();
		var height = contentHeight - toolBarH -131;
		var container = $('.fixed-table-container').css({'height':height})
	}
	function enableChimeTask(){
		let row = $("#chimeTable").bootstrapTable('getSelections')
		if(row.length > 1 || row.length <= 0){
			$.alert('请选择一条报时任务')
			return;
		}
		if(row[0].bEnable+"" == '1'){
			$.alert('当前任务已启用')
			return;
		}
		$.confirm({
			title:'启用报时任务',
			content:'是否启用此报时任务',
			buttons:{
				确认:function (){
					$.ajax({
						url:httpProto+'://'+host+'/control/api_v2.2.5/chime/update/updateChimeStatus.json',
						// url:'http://localhost:8090/control/api_v2.2.5/chime/update/updateChimeStatus.json',
						dataType:'json',
						type:'post',
						data:JSON.stringify({"id":row[0].id,"bEnable":1}),
						contentType:'application/json',
						headers:{
							'Authorization':authForAll
						},
						success:function(result){
							if(result.code == 200){
								$.alert('操作成功！')
								//生成表格
								generChimeTable()
							}else{
								$.alert(result.msg)
							}
							$('#closeChime').click();
						}
					})
				},
				取消:function(){}
			}
		})
	}
	function deactivateChimeTask(){
		let row = $("#chimeTable").bootstrapTable('getSelections')
		if(row.length > 1 || row.length <= 0){
			$.alert('请选择一条报时任务')
			return;
		}
		if(row[0].bEnable+"" == '0'){
			$.alert('当前任务已停用')
			return;
		}
		$.confirm({
			title:'停用报时任务',
			content:'是否停用此报时任务',
			buttons:{
				确认:function (){
					$.ajax({
						url:httpProto+'://'+host+'/control/api_v2.2.5/chime/update/updateChimeStatus.json',
						// url:'http://localhost:8090/control/api_v2.2.5/chime/update/updateChimeStatus.json',
						dataType:'json',
						type:'post',
						data:JSON.stringify({"id":row[0].id,"bEnable":0}),
						contentType:'application/json',
						headers:{
							'Authorization':authForAll
						},
						success:function(result){
							if(result.code == 200){
								$.alert('操作成功！')
								//生成表格
								generChimeTable()
							}else{
								$.alert(result.msg)
							}
							$('#closeChime').click();
						}
					})
				},
				取消:function(){}
			}
		})
	}
	function deleteChimeTask(){
		let row = $("#chimeTable").bootstrapTable("getSelections");
		if(row.length > 1 || row.length <= 0){
			$.alert('请选择一条报时任务')
			return;
		}
		let id = row[0].id;
		$.confirm({
			title:'确认删除',
			content:'确认删除此报时任务?',
			buttons:{
				确认:function(){
					var f = doDeleteChimeTask(id)
					if(f){
						$.alert("删除成功!");
						//生成表格
						generChimeTable()
					}else{
						$.alert("删除失败!");
					}
				},
				取消: function(){}
			}
		})
	}
	function batchDelChime(){
		let row = $("#chimeTable").bootstrapTable('getSelections')
		if(row.length <= 0){
			$.alert('请选择通知任务')
			return;
		}
		$.confirm({
			title:'确认删除',
			content:'确认删除'+row.length+'条报时任务?',
			buttons:{
				确认:function(){
					var fail = []
					for(var i = 0; i < row.length; i++){
						var f = doDeleteChimeTask(row[i].id)
						if(!f){
							fail.push(row[i].id)
						}
					}
					if(fail.length<=0){
						$.alert("删除成功!");
					}else{
						$.alert(fail+"删除失败!");
					}
					//生成表格
					generChimeTable()
				},
				取消:function(){}
			}
		})
	}
	function doDeleteChimeTask(id){
		let flag = false
		$.ajax({
			// url:'http://localhost:8090/control/api_v2.2.5/chime/delete.json',
			url:httpProto+"://"+host+"/control/api_v2.2.5/chime/delete.json",
			type: "post",
			data:JSON.stringify({"id":id}),
			dataType:"json",
			async:false,
			headers:{
				'Authorization':authForAll
			},
			contentType:"application/json",
			success:function(data){
				if (data.statuscode = "000000") {
					flag = true
				}else{
					flag = false;
				}
			}

		})
		return flag
	}






	function selectNum(lowNum,upNum) {
		let numberList = [];
		if(lowNum == upNum){
			numberList.push(lowNum);
			return numberList;
		}
		while(lowNum != upNum){
			numberList.push(lowNum);
			lowNum++;
			if(lowNum == 24){
				lowNum = 0;
			}
		}
		numberList.push(upNum);
		return numberList;
	}
	function addChimeTask(){
		//标识是添加操作
		isChimeEdit = false;
		showChimePlayType(true)
		$('#myChimeModalLabel').html('添加报时任务')
		refreshTreeChime();
		generChimeTimeTable(null);
		generFromData("","Z");
		$("#deptRealIdForChime").val('-2');
		$("#deptInputForChime").val("全部区域");
		if('1' == isAdmin){
			$("#deptRealIdForChime").val('-1');
			$("#deptInputForChime").val("仅管理员可见");
		}else if(deptIdName){
			$("#deptRealIdForChime").val(deptId);
			$("#deptInputForChime").val(deptIdName);
		}
		var length = $("#chimeBootstrap-table").bootstrapTable('getData').length;
		$("#chimeBootstrap-table").bootstrapTable('insertRow',{
			index:length,
			row:{
				index:length,
				One:'00',
				Two:'-',
				Three:'23',
			}
		})
		$("#editChimeModal").modal("show");
	}
	function generChimeTimeTable(times){
		if(times == null || times == "" || times == undefined){
			times = []
		}
		var data=[].concat(times)
		$("#chimeBootstrap-table").bootstrapTable("destroy");
		$("#chimeBootstrap-table").bootstrapTable({
			//showFullscreen:true,
			toolbarAlign:'right',
			toolbar:'#chimeToolbar',
			silent:true,
			data:data,
			striped:true,
			cache:false,
			selectItemName:'btTimeItem',
			//showColumns:true,
			clickToSelect:true,
			uniqueId:'index',
			columns:[{
				checkbox:true,
			},{
				field:'index',
				title:'序号'
			},{
				field:'One',
				title:'开始时间'
			},{
				field:'Two',
				title:'-',
				width:40
			},{
				field:'Three',
				title:'结束时间'
			}],
			onDblClickCell: function(field,value,row,$element){
				var upIndex = $element[0].parentElement.rowIndex - 1;
				if(field == 'One' || field == 'Three'){
					$element[0].innerHTML="<select id='inputCell' type='time' name='inputCell' style='width:auto;'></select>";
					let str = '';
					for (let i = 0; i < 24; i++) {
						let number = i;
						if(number < 10){
							number = "0"+number;
						}
						str += "<option value='"+number+"'>"+number+"</option>"
					}
					$("#inputCell").html(str);
					set_select_checked("inputCell",value)
					$("#inputCell").focus();
					$("#inputCell").blur(function(){
						var newValue = $('#inputCell option:selected').val();
						newValue = newValue.split(":")[0] ? newValue.split(":")[0] : '00';
						row[field] = newValue;
						$(this).remove()
						$("#chimeBootstrap-table").bootstrapTable('updateCell',{
							index:upIndex,
							field:field,
							value:newValue
						});
					})
				}
			}
		})
		$("#chimeBootstrap-table").bootstrapTable('hideColumn', 'index');
		this.checkBox($("#chimeBootstrap-table"))
	}
	function refreshTreeChime() {
		$("#deptTreeForChime").treeview({
			data : allDeptData,// 赋值
			showTags:false,
			levels: 99,
			onNodeSelected: function(event, node) {
				$('#deptInputForChime').val(node.text);
				$('#deptRealIdForChime').val(node.id);
				$('#deptTreeForChime').css('display','none')
			},
		});
	}
	function showChimePlayType(flag){
		if(flag){
			$(".chime-submit-add").show();
			$('.chime-submit-edit').hide();
		}else {
			$(".chime-submit-add").hide();
			$('.chime-submit-edit').show();
		}
	}
	let transferChime = null;
	function initChimeTransfer(data,data1){
		transferChime = new Transfer()
		//显示搜索框
		transferChime.render({
			elem: '#chimeTransferContainer',
			// 全部数据
			data: data,
			width:400,
			// 已选择数据，默认在右边
			value:data1 ? data1 : [],
			title: ['待选分机', '已选分机'],
			// 是否展示关键词搜索
			showSearch: true,
			// 初始化的所有菜单在 右侧 ,默认 左侧
			isRight:false,
			// 菜单二级全展开
			spread:true
		})
	}
